• support@answerspoint.com

Stretch and scale CSS background

2366

Is there a way to get a background in CSS to stretch or scale to fill its container?

2Answer


0

Scaling an image with CSS is not quite possible, but a similar effect can be achieved in the following manner, though.

Use this markup:

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

with the following CSS:

#background {
    width: 100%; 
    height: 100%; 
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0;
}

.stretch {
    width:100%;
    height:100%;
}

and you should be done!

In order to scale the image to be "full bleed" and maintain the aspect ratio, you can do this instead:

.stretch { min-width:100%; min-height:100%; width:auto; height:auto; }

It works out quite nicely! If one dimension is cropped, however, it will be cropped on only one side of the image, rather than being evenly cropped on both sides (and centered). I've tested it in Firefox,Webkit, and Internet Explorer 8.

  • answered 8 years ago
  • B Butts

0

Use the CSS 3 property background-size:

#my_container {
    background-size: 100% auto; /* width and height, can be %, px or whatever. */
}

This is available for modern browsers, since 2012.

  • answered 8 years ago
  • Gul Hafiz

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 2366 times
  • active 9 years ago

Best Rated Questions