O'Reilly logo

Cascading Style Sheets: The Definitive Guide by Eric A. Meyer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Grouping

So far, things have been pretty simple—as long as you only want to apply a single style to a single selector, that is. No doubt you’ll want to go further than that, though: sometimes you’ll want the same style to apply to multiple elements, which means you’ll want to use more than one selector, and other times, you’ll want to apply more than one style to an element or group of elements.

Grouping Selectors

Let’s say you have a document in which both H2 elements and paragraphs should have gray text. The easiest way to accomplish this is to use the following.

H2, P {color: gray;}

By placing both the H2 and P selectors on the left side of the rule and separating them with a comma, we’ve defined a rule where the style on the right (color: gray;) is applied to both selectors. The comma tells the browser that there are two different selectors involved in the rule. Leaving out the comma would give the rule a completely different meaning, which we’ll explore later, in Section 2.5.1.

It is possible to group any number of selectors together. If you wanted to make sure that every element in your document had a color of gray, you might use the following rule:

BODY, TABLE, TH, TD, H1, H2, H3, H4, P, PRE, STRONG, EM, B, I {color: gray;}

As you can tell, grouping allows an author to drastically compact certain types of style assignments which might otherwise result in a very long style sheet. The following two alternatives will have exactly the same result, but it’s pretty obvious which one ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required