Making background image fit any screen resolution with CSS

The usual approach for placing a background image is by placing the background within the body using CSS. No modifications are needed to the HTML file for the background to be displayed.

body
{
	margin:0;
	padding-top:0;
	background:#777;
	color:#f3f3f3;
	font-size:13px;
	background:url(images/main-bg.gif) repeat fixed;
}

However, what if instead of a small repeating image, a much larger, single image is desired. In some resolutions this approach with some slight modifications to the CSS may work, however, will not work in all screen resolutions, making the website look less than satisfactory. For the background image to fit any screen resolution, modifications to the CSS file and HTML will be required. Instead of calling the background from the body using CSS, we will create a div class using CSS for the background image to be called using HTML. Within the HTML somewhere within the body tags, I elected before the content of the site, the following code will need to be added:

<div align="center" >
	<img src="<?php bloginfo("template_url") ?>/images/mybackgroundimage.jpg" border="0" class="bg" >
</div>

Within WordPress, the theme may contain a file called, header.php. It may look similar to this after adding the above code.

<head>
	...
	<?php wp_head(); ?>
</head>
<body>	
	<div class="wrapper">		
		<div class="menu">			
			...
		</div>		
		<div class="top">		
			...	
		</div>	
		<div id="header"/>
		<div align="center" >
			<img src="<?php bloginfo("template_url") ?>/images/mybackgroundimage.jpg" border="0" class="bg" >
		</div>
		<div class="content">

Modify the CSS by removing the image from the body and creating a new class .bg.

body
{
	margin:0;
	padding-top:0;
	font-family:"Myriad web",Tahoma,Verdana,sans-serif;
	color:#f3f3f3;
	font-size:13px;
	background:#1c1c1c;
}

.bg {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: -5000;
}

The results tested by both Firefox and Internet Explorer were a success. However, within Internet Explorer, the page reloads, creating a quick flash effect between pages, to help correct this I added a couple of meta tags to the head of the header.php file. However, I understand that this has been depreciated for IE8 and above.

<!--[if IE]>
	<meta http-equiv="Page-Enter" content="blendTrans(duration=0.01)" />
	<meta http-equiv="Page-Exit" content="blendTrans(duration=0.01)" />
<![endif]-->

A real-world example of this in action may be seen on www.megocollector.com.

Sources
http://thewebthought.blogspot.com/2012/05/css-making-background-image-fit-any.html
http://www.secretgeek.net/fajax.asp

1 Comment

  • contextual backlinks October 11, 2012

    I was recommended this web site through my cousin. I’m no longer sure whether or not this publish is written via him as no one else realize such specified about my trouble. You’re amazing! Thank you!

Comments are closed.