child selectors

Explanation

CSS1 provided the contextual selector which allows the selection of an element that is a descendent of another selector (that's why in CSS2 these are referred to as descendent selectors). But this doesn't provide as much control as we might like. For example, the selector div strong will select <strong> elements inside <div>s, no matter how deeply nested. For example

<div><p>This is the <strong>essence</strong> of the argument</p></div>

is selected, as is

<div>This is the <strong>essence</strong> of the argument</div>

It might be that we only want to select the <strong> element when it is directly within a <div>. We don't want to select them when they are inside another element which is itself inside a <div>. In this case we use the child selector.

You might like to think of child selectors as selecting only children, not grandchildren.

Syntax

A child selector is formed by listing the parent, then the child element separated by a ">". For instance div>strong will select the <strong> element in the following example.

<div>This is the <strong>essence</strong> of the argument</div>

But it will not select it here, where it is not the child of the div.

<div><p>This is the <strong>essence</strong> of the argument</p></div>

More complex selectors can be formed using more than one child. For example div>p>strong will only select strong elements within paragraphs within divs.

Use

Child selectors provide even finer control over the selection of elements than that provided by contextual selectors. As with contextual selectors, they don't require any changes to be made to the HTML.

Browser support

Detailed browser support information for this feature can be found in the full version of the Westciv CSS Guide, or in our CSS Browser Support Table.

next: first child selectors