CSS: Scale background image down if larger than window, keep at 100% otherwise

后端 未结 4 2043
灰色年华
灰色年华 2021-01-12 09:08

I\'d like to deploy a background image in the body of my website that scales down with the window resolution, but does not scale up beyond it\'s original size (1920x1080). T

相关标签:
4条回答
  • 2021-01-12 09:43

    I would use a div as a wrapper with a max-width and set the background to that div.

    HTML

    <body>
     <div class="container">Content</div>
    </body>
    

    CSS

    .container {
      width: 100%;
      max-width: 1920px; /* YOUR BG MAX SIZE */
      background:url("bg.png") no-repeat;
      background-size: 100%;
    }
    
    0 讨论(0)
  • 2021-01-12 09:45

    You could try creating an html <img> tag with a specific id

    e.g.

    HTML

    <img id="mybg" src="path/to/file" alt="never forget the blind folks!" />
    

    CSS

    img#mybg {
        position: fixed; //image will always be top: 0 left: 0 by default.
        display: block; //make it a block for width to work.
        width: 100%; //set default width
        height: 100%; //set default height
        max-width: 1920px; //set max width
        max-height: 1080px; //set max height
        z-index: -999999; //set z-index so it won't overlap any other element.
    }
    

    For dynamic centering you would have to use Javascript in combination with a window.onresize event.

    If you need more information I will edit my post accordingly.

    A good alternative which is very easy to use(but does stretch your background) would be to use jquery backstretch plugin. It allows you to simply add a fullscreen background image, which will scale with resolution (which is not exactly what you want, but the best alternative I could think of).

    0 讨论(0)
  • 2021-01-12 09:47

    You can try like this. Any size image resolution will work like responsive:

    img#mybg {
        position: fixed; //image will always be top: 0 left: 0 by default.
        display: block; //make it a block for width to work.
        width: 100%; //set default width
        height: 100%; //set default height
        max-width: 1920px; //set max width
        max-height: 1080px; //set max height
        z-index: -999999; //set z-index so it won't overlap any other element.
        background-size:100% 100%;
    }    
    
    0 讨论(0)
  • 2021-01-12 10:01

    Just a really small/quick suggestion:

    Depending on how it looks, and all flows together, background-size:contain; might be an option.

    or, on your body, set the max width to 1920, set the margins to auto, and that might also work for you.

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