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 ...

Get Cascading Style Sheets: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.