Recipe 3.6. Using Multiple Background Images on One Selector


Problem

You want to place more than one background image within one CSS selector.

Solution

As of this writing, Safari for Macintosh has implemented the CSS 3 specification for layering multiple background images in one selector.

In CSS 3, the shorthand background property can accept multiple sets of background image information as long as commas separate them (see Figure 3-11):

h2 {  padding-top: 72px; /* enough padding for the images */  text-align: center;  background: url(plane.gif) center no-repeat,    url(mail.gif) top center no-repeat,   url(printer.gif) 40% 24px no-repeat,   url(gift.gif) 60% 24px no-repeat; }  

Figure 3-11. Individual icons are placed as background images in the heading


Discussion

Like most shorthand properties, the shorthand code for multiple backgrounds can be split out into separate CSS declaration blocks.

h2 {  padding-top: 72px; /* enough padding for the images */  text-align: center;  background: url(plane.gif), url(mail.gif), url(printer.gif), url(gift.gif);  background-position: center, top center, 40% 24px, 60% 24px;  background-repeat: no-repeat, no-repeat, no-repeat, no-repeat; }

Since all the backgrounds in the CSS rule do not repeat, one no-repeat value can be placed in the code and applied to all background images:

h2 {  padding-top: 72px; /* enough padding for the images */  text-align: center;  background: url(plane.gif), url(mail.gif), url(printer.gif), url(gift.gif);  background-position: center, top center, 40% 24px, 60% 24px;  background-repeat: no-repeat; }

This reduction of similar values can be applied to all CSS background-related properties making sure that it's desired that the background images share the same value.

For the time being, introducing new elements and applying background images to these new elements is the only way to achieve the technique of multiple images across all modern browsers. For more information and examples on these techniques, see Recipes 3.15 and 3.16 that produce rounded corners with additional markup.

See Also

For more information on the CSS 3 specification for layering multiple images, see http://www.w3.org/TR/2005/WD-css3-background-20050216/#layering.




CSS Cookbook
CSS Cookbook, 2nd Edition
ISBN: 0596527411
EAN: 2147483647
Year: 2006
Pages: 235

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net