Stretch and scale a CSS image in the background – with CSS only – Dev

The best answers to the question “Stretch and scale a CSS image in the background – with CSS only” in the category Dev.


I want that my background image stretch and scale depending on the browser viewport size.

I’ve seen some questions on Stack Overflow that do the job, like Stretch and scale CSS background for example. It works well, but I want to place the image using background, not with an img tag.

In that one an img tag is placed, and then with CSS we tribute to the img tag.

width:100%; height:100%;

It works, but that question is a bit old, and states that in CSS 3 resizing a background image will work pretty well. I’ve tried this example the first one, but it didn’t work out for me.

Is there a good method to do it with the background-image declaration?


You could use the CSS3 property to do it quite nicely. It resizes to ratio so no image distortion (although it does upscale small images). Just note, it’s not implemented in all browsers yet.

background-size: 100%;


CSS3 has a nice little attribute called background-size:cover.

This scales the image so that the background area is completely covered by the background image while maintaining the aspect ratio. The entire area will be covered. However, part of the image may not be visible if the width/height of the resized image is too large.



html,body {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover; /* For WebKit*/
    -moz-background-size: cover;    /* Mozilla*/
    -o-background-size: cover;      /* Opera*/
    background-size: cover;         /* Generic*/


Using the code I mentioned…


<div id="background">
    <img src="" class="stretch" alt="" />


#background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1; /* Ensure div tag stays behind content; -999 might work, too. */

.stretch {

That produces the desired effect: only the content will scroll, not the background.

The background image resizes to the browser viewport for any screen size. When the content doesn’t fit the browser viewport, and the user needs to scroll the page, the background image remains fixed in the viewport while the content scrolls.

With CSS 3 it seems this would be a lot easier.