How to set a minimum width with background-size

后端 未结 4 557
伪装坚强ぢ
伪装坚强ぢ 2021-01-04 06:46

I have an image that is 1000px X 600px . I want to use it as a responsive background for a div but would like to set a minimum width of 1000px despite how small the browser

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 07:01

    If media queries are an option, you can setup a media query for browser viewports smaller than 1000px wide.

    Assuming your HTML viewport is set:

    
    

    And your div is named 'bg':

    In your CSS:

    .bg {
        width: auto; /* Scale the div to the parent width */
        height: 900px; /* The div needs some height to be visible */
        background-image: url(bg.png); /* This is your background image */
        background-size: 100%; /* Always size the image to the width of the div */
        background-position: top; /* Position the image to the top center of the div */
    }
    
    /* For any viewports less than 1000px wide */
    @media (max-width: 1000px) {
    
        .bg {
            background-size: 1000px 600px; /* Force the image to its minimum width */
        }
    
    }
    

提交回复
热议问题