Wednesday, January 12, 2011

IE 7/8 stretching background image to 100% width and height


CSS3 does present a superb & hassle-free way of developing web pages, but Microsoft’s IE 7 and 8 browsers don’t support CSS3 properties. It’s a big headache – ain’t it? Microsoft engineers have done a great job with IE8 at least 8 doesn’t act very weird as compared to 7. IE7 has tons of limitations when it comes to CSS based layouts, one of them is stretching background image to 100% width and height regardless of screen resolution.

Instead of calling it limitations I would say IE 7 prefers eating stuff little differently. So we need to go beyond enemy lines here :)

Stretching background image to 100% width and height is possible in IE 7/8 with CSS2 (CSS3 is way better than this. We only need to use ‘cover’ or ‘size’ property of it).

Here is the code – (I wish someday blogger will allow me attach file with posts. I really don’t prefer putting code on blog like this but I absolutely have no another option).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Stretching background image to 100% width and height</title>

<style type="text/css">
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
img#bg{
  position:fixed;
  top:0;
  left:0;
  width:100%;
  height:100%;
}
#content {
  position:relative;
  z-index:1;
}
</style>

<!--[if IE 6]>
<style type="text/css">

html { overflow-y: hidden; }
body { overflow-y: auto; }

img#bg { position:absolute; z-index:-1; }

#content { position:static; }

</style>
<![endif]-->


</head>

<body>

<img src="size-bg.jpg" alt="background image" id="bg" />
<div id="content">Your website content.</div>

</body>

</html>