Hey Readers!
This blog post is going to solve the problem you must have faced sometime while putting a background image. There are situations when we want the background image to fill the entire div (instead of the viewport) without distorting. That is, the dimensions stay proportional.
A solution we would have used long back is :
#bg {
/* Preserve aspet ratio */
min-width: 100%;
min-height: 100%;
}
or
background-size:100%;
We could also give exact dimensions of the background image.
But CSS3 gives a more dynamic solution to this.
While stretching the background-image, we have the following points in mind-
- Fills the entire div leaving no white space
- Images are scaled as required
- Image proportions are retained (known as aspect ratio)
- Image is centered inside the div
- Compatible in as much browsers as possible
We can do this very easily, thanks to the background-size
property in CSS3. We set the background fixed and centered, then just adjust the size using background-size
set to 'cover'.
Here is the code :
.div{
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
And that is it.
Keep Coding!
0 Comment(s)