Combining Selectors

Often you will need to combine various selectors in a single rule to get the effect that you require. The sidebar on the right shows some simple examples of combining selectors.

Changing The Heading

You can see the normal appearance for the h3 element on these pages in the heading for this subsection. However, the heading of the sidebar is also an h3 element, but it looks different. This is because there is a rule with the following format:

div.sidebar h3 {
    line-height: normal;
    margin-top: 3px;
    font-style: italic;
    margin-bottom: 5px;
    color: #600;
}

The selector for this rule only applies to h3 elements that are inside a div element which has the class sidebar applied to it. This means that other h3 elements in the document are not affected by the rule.

Note that the spacing (and lack of space) in the selector is crucial here. Specifically, the rule above would apply in the following example:

<div class="sidebar"><h3>Heading Example</h3>
<p>If we want to change the style of an element within a particular context, whilst leaving their appearance untouched elsewhere, we need to combine selectors.</p>
</div>

But it would not apply in the case of the following code:

<div><span class="sidebar"><h3>Heading Example</h3></span>
<p>If we want to change the style of an element within a particular context, whilst leaving their appearance untouched elsewhere, we need to combine selectors.</p>
</div>

The differences between the two code snippets are highlighted in red. This is because the rule specifically says that the h3 element must be inside a div with the class sidebar. It is in the first example, but in the second example the containing div does not have any class and the sidebar class is applied to a span element. If, however, the selector for the rule was changed so that instead it read

div .sidebar h3 {
    
}

Then it would apply, because now it says apply to an h3 element inside an (any) element which has the class sidebar which is then contained within a div. What is the difference between the selector shown immediately above and the original version? Don't see it?

Thus, you now see one of the key difficulties that beginners face when working with computer code: small differences in punctuation that sometimes humans don't even notice can make a big difference to the way that the computer interprets the code! It is vital, if you are going to learn to read and write code, that you develop an good eye for detail.

Further Reading

The following links contain some good information about selectors and how to combine them:

You can find some good examples of combining selectors on Ironspider:

A very good set of examples of selectors with demos is at NetTuts+:

If you want a concise, to the point technical reference, the W3Schools is your page:

The next page discusses inline styles... Next