× Introduction Applying CSS CSS Syntax CSS Selectors Grouping Color Background CSS Fonts CSS Text CSS Links Gradients The Box Model Margin and Padding Border Outline Measurement Units Dimension CSS Quick Reference Examples Projects eBooks






Grouping

In this tutorial you will learn how to group CSS selectors for applying style rules to elements.

To keep style sheets short and easy to edit, similar rules can be grouped together. This grouping provides several ways to specify a set of related rules.

Ungrouped Rules

Each rule can be written separately, which allows you to apply individual style rules to each selected element.

Example: Try It

h1 { color: red; }
h1 { background: black; }
h2 { color: red; }
h2 { background: black; }

Grouped Selectors

The selectors can be grouped together by separating them with a comma. This will apply the declaration to both selectors.

Example: Try It

h1, h2 { color: red; }
h1, h2 { background: black; }

Grouped Declarations

The declarations can be grouped together by separating them with a semicolon. All styles within the declaration block will be applied to the selector.

Example: Try It

h1 {
color: red;
background: black;
}

Grouped Selectors and Declarations

Both the selectors and declarations can be combined, resulting in a single rule. This method offers the most concise way to write these rules.

Example: Try It

h1, h2 {
color: red;
background: black;
}

Rules should be grouped whenever possible to make the style sheet more succinct. This has a small performance benefit because concise rules reduce the size of the style sheet, which makes the CSS file load more quickly. Moreover, it is convenient to specify the properties in only one place, in case they have to be changed later. Additionally, grouping selectors with similar styles makes it easier to maintain consistency between them.