CSS HTML

[Solved – 9 Answers] CSS -HTML – Stretch and scale a CSS image in the background – with CSS only

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

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:
css code
background: url('imgwiki.png') no-repeat; 
background-size: 100%;

  • 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;
}
See also  [Solved - 7 Answers] How do you keep parents of floated elements from collapsing

About the author

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

1 Comment

Click here to post a comment

X