More Web Design Tutorials

Adding Multiple Background Images

March 22, 2011

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.