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

守給你的承諾、 提交于 2019-12-01 03:58:30

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%;
}

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.

vadlamani

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%;
}    

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!