Skip to main content

CSS Selectors

CSS Group Selector

Written by Updated CSS Group Selector exercises

Combine selectors into a selector list when several elements share declarations, while understanding how one invalid selector can affect the rule.

A comma in a selector means "and also". h1, h2, p { color: blue; } styles headings and paragraphs with one rule instead of three. That is the whole idea of grouping.

It works with any selectors, not just element names, so you can mix types, classes and IDs in one list. The selectors themselves are explained in CSS Element Selector.

Group Selector Syntax

css

selector1, selector2, selector3 {
    property: value;
}

Group Selector Example

css

h1, p {
color: blue;
}

That turns both the h1 and every p blue.

Before and after grouping

css

/* Three rules repeating the same thing */
h1 { font-family: Georgia, serif; }
h2 { font-family: Georgia, serif; }
.title { font-family: Georgia, serif; }

/* One rule */
h1, h2, .title { font-family: Georgia, serif; }

One bad selector breaks the whole group

If any selector in a normal list is invalid or unsupported, the browser throws away the entire rule, not just that one selector. So h1, p, :unknown-thing { color: blue; } styles nothing at all.

The functional pseudo-classes :is() and :where() are "forgiving": an unknown selector inside them is skipped and the rest still work. They also make long groups shorter:

Grouping with :is()

css

:is(article, section, aside) h2 {
  margin-top: 0;
}

Example

Group Selector Complete Example

html

<!DOCTYPE html>
<html>
<head>
    <title>CSS Group Selector</title>
    <style>
        h1, p {
            color: blue;
            text-align: center;
        }
    </style>
</head>
<body>

    <h1>Group Selector Example</h1>

    <p>This paragraph is styled using group selector.</p>

    <p>All selected elements share the same styles.</p>

</body>
</html>

The heading and both paragraphs come out blue and centered, all from one rule.

Browser Support

Feature
Chrome
Edge
Firefox
Safari
Selector list11211

Versions show the first stable desktop release with unprefixed support. Data source: MDN Browser Compatibility Data 8.0.8.

Good to know

  • A trailing comma, as in h1, p, { }, makes the whole rule invalid.
  • Grouping is only about sharing styles. Each selector keeps its own specificity.
  • Put each selector on its own line when the list gets long. It is easier to read and to change.

CSS Group Selector exercises

Two headings

Make both headings green with one rule.

The HTML your code works on
<h1>Shop</h1>
<h2>Fruit</h2>
<p class="lead">Fresh fruit.</p>
<p id="tip">Tip</p>
<a href="#">Buy</a>

Result

Check your answer to see it here.