How to Stretch and scale a CSS image in the background – with CSS only ?

  • use the CSS3 property to do it .
  • It resizes to ratio so that no image distortion will happen (although it does upscale small images).
  • Just note, it’s not implemented in all browsers yet.
css code
background-size: 100%;

  • CSS3 has a attribute called background-size:cover.
  • This does not stretch the image, but it will crop the image accordingly.

HTML :

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

CSS :

css code
#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
{
width:100%;
height:100%;
}
[ad type=”banner”]

CSS :

css code
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*/
}

css code
background-size: 100% 100%; 
  • It stretches bg to fill entire element on both axis

  • Use this
css code
background: url('imgwiki.png') no-repeat; 
background-size: 100%;
[ad type=”banner”]

  • You can add this class into your CSS file.
css code
.stretch 
{
background: url(images/wikitechy.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

  • In order to scale your images appropriately based on the container size , here is the following code :
css code
{
background-size:contain;
background-repeat: no-repeat;
}

  • We can do this through the CSS background-size property in CSS3.
  • We’ll use the html element (better than body as it’s always at least the height of the browser window).
  • We set a fixed and centered background on it, then adjust it’s size using background-size set to the cover keyword
CSS code
html 
{
background: url(images/wiki.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
[ad type=”banner”]

Categorized in: