How to set a minimum width with background-size

后端 未结 4 536
伪装坚强ぢ
伪装坚强ぢ 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 06:52

    There's now an option for background-size to only scale the image until the picture has met it actual height/width. This way, you don't have to set a min-width or anything.

    In your CSS:

    body {
      background-size: cover;
    }
    

    Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size#Values

    0 讨论(0)
  • 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:

    <meta name="viewport" content="width=device-width">
    

    And your div is named 'bg':

    <div class="bg"></div>
    

    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 */
        }
    
    }
    
    0 讨论(0)
  • 2021-01-04 07:11

    I had the same problem. The following code worked for me. I just had to add a min width in the same element. Here I just used the html element, I would assume that it would be more conventional to use the body element

         /* CSS Style Sheet */
    
     html    { background-image:url(example.JPG);
                        background-size:cover;
                        min-width:1000px;}
    

    I hope this helps,

    0 讨论(0)
  • 2021-01-04 07:16

    You can use calc in background-size:

    .bg {
        background-size: calc(max(100%, 1000px));
    }
    

    calc works also with background-position, for one side, or both sides

    0 讨论(0)
提交回复
热议问题