O'Reilly logo

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

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