Background Stretch and scale in CSS 100%

Background Stretch and scale in CSS is what you will need to do in responsive html slicing all of time. My situation happen all of times so that I share you this way to help you and remind me when I need it.

css style background

The key and the magic to show background of a css layer in 100% scale is background-size. Just use it like this

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

To preserve the aspect ratio of the image you should use “background-size: cover;” or “background-size: contain;”.

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

Use this html:

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

Reference: http://stackoverflow.com/questions/376253/stretch-and-scale-css-background

4 comments

  1. You save me many hours to research. Thanks guy

  2. Simple and useful CSS tips, thanks man.

  3. That ‘s really useful. Thanks for a good tips about CSS. It ‘s nice to add more bookmark from you

CDN by MaxCDN