Grouping

So far, we’ve learned fairly simple techniques for applying a single style to a single selector. But what if you want the same style to apply to multiple elements? If that’s the case, you’ll want to use more than one selector or apply more than one style to an element or group of elements.

Grouping Selectors

Let’s say you want h2 elements and paragraphs to have gray text. The easiest way to accomplish this is to use the following declaration:

h2, p {color: gray;}

By placing the h2 and p selectors on the left side of the rule and separating them with a comma, you’ve defined a rule where the style on the right (color: gray;) applies to the elements referenced by 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.2.

There are really no limits on how many selectors you can group together. For example, if you want to display a large number of elements in gray, you might use something like the following rule:

body, table, th, td, h1, h2, h3, h4, p, pre, strong, em, b, i {color: gray;}

Grouping allows an author to drastically compact certain types of style assignments, which makes for a shorter style sheet. The following alternatives produce exactly the same result, but it’s pretty obvious which one is easier to type:

h1 {color: purple;} h2 {color: purple;} h3 {color: purple;} h4 {color: purple;} h5 {color: purple;} ...

Get Cascading Style Sheets: The Definitive Guide, Second Edition 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.