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.
- CSS3 has a attribute called background-size:cover.
- This does not stretch the image, but it will crop the image accordingly.
HTML :
[pastacode lang=”markup” manual=”%3Cdiv%20id%3D%22background%22%3E%0A%20%20%20%20%3Cimg%20src%3D%22imgwiki.jpg%22%20class%3D%22stretch%22%20alt%3D%22%22%20%2F%3E%0A%3C%2Fdiv%3E%0A” message=”html code” highlight=”” provider=”manual”/]CSS :
[pastacode lang=”css” manual=”%23background%20%0A%7B%0A%20%20%20%20width%3A%20100%25%3B%20%0A%20%20%20%20height%3A%20100%25%3B%20%0A%20%20%20%20position%3A%20fixed%3B%20%0A%20%20%20%20left%3A%200px%3B%20%0A%20%20%20%20top%3A%200px%3B%20%0A%20%20%20%20z-index%3A%20-1%3B%20%2F*%20Ensure%20div%20tag%20stays%20behind%20content%3B%20-999%20might%20work%2C%20too.%20*%2F%0A%7D%0A.stretch%20%0A%7B%0A%20%20%20%20width%3A100%25%3B%0A%20%20%20%20height%3A100%25%3B%0A%7D%0A” message=”css code” highlight=”” provider=”manual”/] [ad type=”banner”]CSS :
[pastacode lang=”css” manual=”html%2Cbody%20%0A%7B%0A%20%20%20%20background%3A%20url(images%2Fbg.jpg)%20no-repeat%20center%20center%20fixed%3B%0A%20%20%20%20-webkit-background-size%3A%20cover%3B%20%2F*%20For%20WebKit*%2F%0A%20%20%20%20-moz-background-size%3A%20cover%3B%20%20%20%20%2F*%20Mozilla*%2F%0A%20%20%20%20-o-background-size%3A%20cover%3B%20%20%20%20%20%20%2F*%20Opera*%2F%0A%20%20%20%20background-size%3A%20cover%3B%20%20%20%20%20%20%20%20%20%2F*%20Generic*%2F%0A%7D%0A” message=”css code” highlight=”” provider=”manual”/] [pastacode lang=”css” manual=”background-size%3A%20100%25%20100%25%3B%20%0A” message=”css code” highlight=”” provider=”manual”/]- It stretches bg to fill entire element on both axis
- Use this
- You can add this class into your CSS file.
- In order to scale your images appropriately based on the container size , here is the following code :
- 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
Very nice
Good
Great
All the solutions are useful and easy
Nice one
good