The CSS Grouping Selector allows you to apply the same styles to multiple selectors using a single CSS rule. Instead of writing separate rules for headings, paragraphs, and other elements, you can group them together using commas.
Grouping selectors helps reduce repeated CSS code and makes stylesheets easier to read and maintain.
CSS Grouping Selector Syntax
The syntax for a grouping selector is:
selector1, selector2, selector3 {
property: value;
}
Separate each selector with a comma. The styles inside the braces apply to every selector in the group.
CSS Grouping Selector Example
The following example applies the same text color and font family to headings and paragraphs.
<!DOCTYPE html>
<html>
<head>
<title>CSS Grouping Selector</title>
<style>
h1, h2, p {
color: blue;
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to Web4Learners</h1>
<h2>Learn CSS</h2>
<p>Explore web development tutorials.</p>
</body>
</html>
In this example, the <h1>, <h2>, and <p> elements all receive blue text and the Arial font family.
Grouping Different CSS Selectors
You can group element selectors, class selectors, and ID selectors in the same rule.
h1, .highlight, #main-title {
color: darkblue;
text-align: center;
}
This rule applies the specified styles to all <h1> elements, elements with the highlight class, and the element with the main-title ID.
Learn more about these selectors in our CSS Element Selector, CSS Class Selector, and CSS ID Selector tutorials.
Why Use CSS Grouping Selectors?
Grouping selectors reduces duplicated declarations and keeps your CSS organized. For example, instead of writing three separate rules for headings, you can combine them into one rule.
h1 {
color: green;
}
h2 {
color: green;
}
h3 {
color: green;
}
You can simplify the same code to:
h1, h2, h3 {
color: green;
}
Both examples apply green text to the three heading levels. The grouping selector is especially useful when several elements share the same styling.