Grouping CSS Styles

If the same set of properties are to be assigned to more than one selector one can list the selectors together thus:

.selectorA,.selectorB,...,.selectorN

This technique is known as grouping. Note that Firefox, like the W3C style validator, puts a space between each member of the group. Thus, selector grouping above will turn up in Firefox as

.selectorA, .selectorB,..., .selectorN

IE, on the other hand, separates grouped selectors into a sequence of individual rules. So why does this matter? It matters when you want to manipulate CSS rules in JavaScript using the cssRules property (Firefox and Opera) or the rules property (IE). In the latter case locating a named selector is a simple matter of looping through the sequence of rules. FireFox you must parse each selector grouping you encounter to establish if the rule in question is listed there. However, in light of the discussions on nesting and specificity that follow you will see that the Firefox way is in fact the correct one.

Nesting CSS Styles

A related technique is nesting selectors. A typical example of nesting is

div a{ color: red; font-family: arial }

This code specifies that all anchor tags inside a div element should use the arial font and be shown in red. It is not unusual to apply the same style to some/all child elements contained by a block element, such as div. Using a nested CSS specification as opposed to a class="selector" declaration within each element tag results in code that is both more compact and a great deal easier to maintain. On this site we have used rule nesting to define heading and bulleted/numbered list, formats. We recommend that you make good use of the intrinsic HTML h#tags - styled to your tastes and needs, of course - as opposed to a style definition all of your own. Why? It is possible, though we emphasize that we have no insider knowledge, that search engine robots assign greater weightage to text wrapped in h# links when they crawl your site.

The nesting technique described above is called descendant nesting. While it is useful its all or nothing nature can at times get quite obstructive. A more selective technique is child nesting

.info>a{ color: red; font-family: arial }

Here we specify that all anchors that are directly owned - i.e. children of - by block elements using the selector info should be styled as indicated. This ensures that anchors owned by nested block elements are not affected. Unfortunately, this feature is not supported by IE6.

A related technique, once again not supported by IE6 uses the :first-child pseudo-class.

CSS grouping and nesting rules are a very powerful construct that can be used to deliver extremely targeted styling of an HTML document. An excellent example of the use of these principles is available here: Word 2003 Table Styles using CSS

Jump To...

Colophon