News & UpdatesProgrammingWeb programming Store My Projects
Links
Affiliates

CSS Tutorial – 04 – Grouping

CSS tutorials

To keep style sheets short and easy to edit similar rules can be grouped together. This gives several ways of specifying a set of related rules. For example, coloring the text red and the background black for two header elements can be done in basically four different ways.

Ungrouped rules

First, each rule can be written separately.

h1 { color:      #FF0000; }
h1 { background: #000000; }
h2 { color:      #FF0000; }
h2 { background: #000000; }

Grouped selectors

Second, the selectors can be grouped together by separating them with a comma. This kind of grouping will make a style apply to multiple selectors.

h1, h2 { color:      #FF0000; }
h1, h2 { background: #000000; }

Grouped declarations

Third, the declarations can be grouped together by separated them with a semicolon. All styles within the declaration block will be applied to the selector. The last semicolon is not necessary, but it’s a good practice to include it.

h1 { color:      #FF0000; 
     background: #000000; }
h2 { color:      #FF0000; 
     background: #000000; }

Grouped selectors and declarations

Fourth, both the selectors and declarations can be combined, resulting in a single rule.

h1, h2 { color:      #FF0000; 
         background: #000000; }
Recommended additional reading:
Sams - Teach Yourself HTML and CSS in 24 Hours