How to Stretch a Background Image in CSS

Stretching background images becomes easy with the new CSS version 3 that comes up with the property named as background-size. Since CSS3 is not yet fully implemented in different browsers, life not easy, you have to stick with lengthy trick of stretching background images. In this how-to we discussed both of them.

In order to stretch background images in a particular page, there are few options. Best and easy one is to use the background-size property that is tailor-made to do so, but due to limited support CSS3 in browsers currently, another way to do this task is to make background image fake to make it stretch. Lets discuss both of them.

Stretching a Background Image using CSS 3

You can easily make background image of a particular web page to stretch by applying background-size property.

1
2
3
4
5
6
7
body {
background: url(backround_image.png) no-repeat;
background-size: 100%;
}

Stretching a Background Image by Faking It

At present CSS 3 is not fully implemented in common browsers. Another way of doing this is to stretch it across the whole page.

Step 1

Set the height to 100%,  0 margin, and o padding.

1
2
3
4
5
6
7
8
9
10
11
12
13
<style type="text/css">
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>

Step 2

Set the image that you want to make as background image right after the body tag.

1
2
3
4
5
<body>
<img src="background-image.jpg" alt="BG Image" id="bg" />
</body>

Step 3

Position the image as fixed with 100% width and 100% hieght.

1
2
3
4
5
6
7
8
9
10
11
12
13
img#bg {
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
}

Step 4

Make your content’s position relative and z-idex 1.

1
2
3
4
5
6
7
#content {
position:relative;
z-index:1;
}

Step 5

But this can create some problems with Internet Explorer 6, so add following code to get manage this problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!--[if IE 6]>
<style type="text/css">
html { overflow-y: hidden; }
body { overflow-y: auto; }
#bg { position:absolute; z-index:-1; }
#content { position:static; }
</style>
<![endif]-->


Related posts

2 Responses

By Mobie

June 30, 2011

How come you never show all the code together! Complete. Just pieces here and there. Come on. I have tried for an hour.

There are two parts the BG Body Tag and The CSS. How do they all fit together. Please show. Thanks

By Gatis

November 28, 2011

Hi,

I tested this method, but there’s a problem: if you put a flash content on top of this stretched (faked) background-image, then the whole site starts to lag (more in IE). Do you think there’s some solution to avoid that?


Post your response

Copyright © 2010 - 2014 Handy CSS Designed By Anotix, Powered By WordPress, all right reserved.