Westciv Logo

These materials are copyright Western Civilisation Pty Ltd.

www.westciv.com

They are brought to you courtesy of Style Master CSS Editor and Westciv's standards based web development courses.

Please see our website for detailed copyright information or contact us [email protected].

complete css guide

Child selectors

Browser support

Get browser support information for child selectors in the downloadable version of this guide or our browser support tables.

Explanation

CSS 1 provided the descendant selector which allows the selection of an element that is a descendant of another selector. But this doesn't provide as much control as we might like. For example, as we saw in the descendant selector section of this guide 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 <strong> elements 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, which was introduced with CSS 2.

In terms of the containment hierarchy 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 descendant selectors. As with descendant selectors, they don't require any changes to be made to the HTML.