CSS3 Multiple Backgrounds

CSS3 has a nifty feature that I wasn’t aware of until recently: multiple backgrounds per element. This was something I used to wish for frequently before I got used to faking it by nesting DIVs and assigning them single backgrounds. Chris Coyier’s CSS-Tricks blog pointed this neat part of the spec out.

The syntax is easy, you just comma separate them. I find it’s easiest/best to use the background shorthand property so you can declare the position and repeating and whatnot and keep them all grouped together. What isn’t obvious while looking at the syntax is which image is on top in the vertical stacking order when those images overlap. The spec is clear in this regard and browser implimentations follow. The first is on top and they go down from there.

The syntax looks something like this:

/* Fallback for older browsers */
background: url(fallback.png) 0 0 no-repeat;

/* Multiple backgrounds! */
url(top.png) 0 0 no-repeat,
url(middle.png) 100px 0 no-repeat,

Is that cool or what?

If having missing images just isn’t acceptable for your site, you can use a little “hack” to load a fallback background. Placing the first background property seen in the above code snippet will allow for graceful degradation, as older browsers will simply ignore the newer version of the background declaration. It has the disadvantage of loading it anyway with newer browsers, though. I think a better option is using the single-property for design-critical images that need to load in any browser and using the other for progressively enhancing elements.