Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Simple Selectors  ›  Lesson

Grouping Selectors

grouping 12 minA comma-separated selector list applies one declaration block to several independent selectors, each keeping its own specificity, and one invalid item drops the whole rule.

Grouping Selectors

The café's h1, h2 and h3 should all use the same serif font. You could write three identical rules, then remember to edit all three whenever the font changes. Or you could write one rule with a list of selectors.

The rule

A comma means "and also": one block, several independent selectors.

h1,
h2,
h3 {
  font-family: Georgia, serif;
  color: navy;
}

Every example uses the Harbour Café page from the first lesson of the course: a header with an h1 and a nav of two links, a section#menu holding an h2 and two article.dish cards (the second is also .special), each with an h3, a p.price and a description p, then a section#visit with an h2 and one p, and a footer with one p.

A selector list is several selectors separated by commas. The declarations apply to anything matched by any of them. Writing each selector on its own line keeps long lists readable.

Each item in the list is independent:

  • Each keeps its own specificity. In h2, #visit p, the h2 headings get the declarations at (0,0,1), not at the id's weight.
  • The comma is not a space. h2, .price selects headings and prices; h2 .price selects prices inside headings, which on this page is nothing.

One sharp edge: if any selector in a plain list is invalid, the browser drops the whole rule. A typo in one item switches off the styles for all the others. (The newer :is() and :where() wrappers are forgiving about this, but a bare comma list is not.)

The shortcut

Say "and also" at each comma, and test each item alone. If any item would be invalid on its own, the whole group is dead.

Grouping the price stylesStep 1 of 4
  1. The goal

    Prices and the "Today's menu" heading should share the same accent colour.

Drills

Answer fast — trust the rule.

quick drill

How many elements does h2, .price match on the café page?

quick drill

How many elements does h2 .price (no comma) match?

quick drill

A rule's selector is h2, .price, .3-for-2. What gets styled?

quick drill

In h3, #menu .price { color: teal; }, what specificity do the h3 headings get?

Remember

  • A comma means "and also"; each selector in the list is independent.
  • Each item keeps its own specificity.
  • One invalid item kills the whole list, and a missing comma changes the meaning.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe missing styles

A rule reads h1, h2, h3, .price, .2for1 { color: navy; } and nothing turns navy. Explain why, how to fix it, and why the comma matters compared with writing h2 .price.