CSS: scale the background image down if it is larger than the window, save 100% otherwise

I would like to expand the background image in the body of my website, which scales with the resolution of the window, but does not scale outside its original size (1920x1080). That way, users with lower resolutions can see the whole image, but those that are outside don't have an ugly scaled background.

This is not like background images supporting properties such as max-width, which I would normally use for this purpose.

What could be the solution? Is this possible in CSS without additional scripts?

+6
source share
4 answers

I would use a div as a wrapper with maximum width and set the background for this 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%; } 
+9
source

Just a very small / quick suggestion:

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

or, on your body, set the maximum width to 1920, set the margins automatically, and this may also work for you.

+4
source

You can try this. Resolution of any size will work as 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%; } 
+3
source

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

eg.

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 will have to use Javascript in conjunction with the window.onresize event.

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

A good alternative that is very easy to use (but stretches your background) would use a jquery backstretch plugin . This allows you to simply add a full-screen background image that will scale with resolution (which is not exactly what you want, but the best alternative I could think of).

+1
source

Source: https://habr.com/ru/post/957036/


All Articles