Grouping selectors

Selectors are used to "select" the elements on an HTML page that are affected by rules. When several selectors share the same declarations, they may be grouped together to save writing the same rule more than once. Each selector must be separated by a comma. They can also include a wide range of selectors. For example:

h1, h2, h3, h4 { padding: 1em; }
.highlight p, .highlight ul { margin-left: .5em; }
#main p, #main ul { padding-top: 1em; }

There are two common mistakes that people make when grouping selectors. The first is forgetting to write each selector in full. For example, if you are trying to target two elements within the same containing block, and with the same ID, chances are you will probably want them to be written in the same way. So, this is probably wrong:

#maincontent p, ul { border-top: 1px solid #ddd; }

The correct group selector would more likely be:

#maincontent p, #maincontent ul { padding-top: 1em; }

The second common mistake is to end the grouping with a comma. This can cause certain browsers to ignore the rule entirely.

.highlight p, .highlight ul, { margin-left: .5em; }

Further information

Shorthand rules »

Other Max Design articles and presentations
Associated with