CSS Grouping Selectors

Grouping selectors with commas lets a single rule style many different elements at once, so you never repeat the same declarations.

Why group selectors

Sometimes several elements should share the same styling. Instead of writing separate rules with identical declarations, you can list all the selectors in one rule, separated by commas. Every listed selector receives the same declaration block.

The repetitive way

Without grouping, giving three headings the same color means repeating yourself three times. If the color ever changes, you have to edit every copy.

Repeated rules

<!DOCTYPE html>
<html>
<head>
<style>
h1 {
  color: #00643c;
}
h2 {
  color: #00643c;
}
h3 {
  color: #00643c;
}
</style>
</head>
<body>

<h1>Heading One</h1>
<h2>Heading Two</h2>
<h3>Heading Three</h3>

</body>
</html>

The grouped way

Comma-separating the selectors collapses all three rules into one. Now a single edit updates every heading at once.

One grouped rule

<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, h3 {
  color: #00643c;
  font-family: Arial, sans-serif;
}
</style>
</head>
<body>

<h1>Heading One</h1>
<h2>Heading Two</h2>
<h3>Heading Three</h3>

</body>
</html>
  • Less code to write and read
  • One place to make changes, so styles stay consistent
  • Works with any mix of element, class, and id selectors
Note: The comma is essential. Writing <h1 h2 h3> without commas creates a descendant selector that means something completely different: an h3 inside an h2 inside an h1.

Mixing selector types

<!DOCTYPE html>
<html>
<head>
<style>
h1, .lead, #intro {
  margin-bottom: 16px;
}
</style>
</head>
<body>

<h1>Welcome</h1>
<p class="lead">A brief intro paragraph.</p>
<div id="intro">More introductory text.</div>

</body>
</html>