Multiple Background Images with CSS

At times, it makes more sense to use background images than to insert them directly into the page. And while each element – like your body tag – can hold only one background image, they can be applied to several elements.

But pretty much every selector can hold a background image. On THIS PAGE, I have added the image to the html tag, the body tag, and the h1 and h2 tags (these are ’selectors’) – like so:

body {
	background: url(bgimage.jpg) repeat-y right;
}
 
html {
	background: url(bgimage.jpg) repeat-y left;
}
 
h1 {
	background: url(bgimage.jpg) no-repeat right;
}
 
h2 {
	background: url(bgimage.jpg) no-repeat left #ffc;
	padding-left: 250px;
	height: 150px;
}
 
#wrapper {
	padding: 0 250px; 
/*I'm using the right and left padding of the wrapper to keep
the content off the images */
}

Note that I’m a bit lazy at the moment, and am using the same image for all four selectors. Taking a closer look at each of them, also shows a bit more how things work:

The html tag (image displayed on the left) repeats the flower all the way down the monitor, regardless of how much content there is. Resize your window and see what happens.

The body tag, where the image is displayed to the right, only shows the image as far as the content goes.

The h1 tag only shows as much of the image as the space its content is taking up.

The h2 tag also has some height added to it (exactly 150px, the height of the background image), so it does show the entire image. I’ve also added the background color to more clearly demonstrate the space that’s taken up by h2.

Tags:

This post was written by: Andrea Barnett

This entry was posted on Saturday, May 8th, 2010 at 11:48 am and is filed under CSS Basics, CSS Misc, CSS Page Layouts, Killer CSS Tips and Tricks. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Multiple Background Images with CSS”

  1. James Winthrop says:

    This is not a good solution. Have you checked it in multiple browsers, including IE 7? There is a large gap on the right hand side where the image is supposed to be…

  2. Andrea says:

    The page looks fine in IE7 (same as in FX and IE8) – what specifically are you talking about? Note that the background image applied to the body tag only shows to the extend of content, not the entire monitor area as does the one applied to the html tag.

Leave a Reply