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). That way, users with smaller resolutions can still see the entire image, but those beyond do not have an ugly upscaled background.
It doesn't look like background images support properties like max-width, which I would usually use for a purpose like that.
What could the solution be? Is this possible in CSS without extra scripting?
The background-size CSS property lets you resize the background image of an element, overriding the default behavior of tiling the image at its full size by specifying the width and/or height of the image. By doing so, you can scale the image upward or downward as desired.
Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.
The Simple Solution Using CSSBy setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.
Use background-size property to cover the entire viewport The CSS background-size property can have the value of cover . The cover value tells the browser to automatically and proportionally scale the background image's width and height so that they are always equal to, or greater than, the viewport's width/height.
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.
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%;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With