CSS rules can apply to more than one element on the web page. For example, if I create a rule like
body {
font-family: Arial, Helvetica, sans-serif;
}
everything on the page will use that rule because of inheritance. Everything on the page is a descendant of the body element, so everything on the page will display in the specified font. But there is another way to style elements within the cascade that lets you choose more specific targets for your styles.
If you want a few elements to display in a specific way, you can style them with a group selector. A group selector is nothing more than a comma separated list of selectors that all share the same rule. To stick with the font-family example, if you want everything on the page to be in a sans-serif font except the headings, you can add a rule after the rule above with a group selector for headings. (When the body
rule is first in the cascade, adding a rule later in the cascade will overrule the style set in the body
rule for the selected elements.) Like this:
h1, h2, h3, h4, h5, h6 {
font-family: Georgia, 'Times New Roman', serif;
}
Now the headings have a serif font.
Note that the difference between a descendant selector and a group selector is the presence of a comma.
Grouped selectors can contain IDs, classes, descendant selectors, pseudo elements and any other selector you can use in CSS. Here’s a more complex example with three grouped selectors:
a:active, div.entry-content a:active, body.single div.entry-meta a:active, div.comments ol.commentlist a:active {
color:#aaa;
}
Using group selectors saves time and bandwidth in your CSS, because it styles several elements with one rule.
One thought on “Grouping CSS Selectors”