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

Adjacent selectors

Browser support

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

Explanation

Most of the complex selectors we've seen select on the basis of containment. For example the child selector selects elements that are the children of other elements, and the descendant selector selects any descendant elements.

Adjacent selectors are similar, but select sibling elements (that is, elements with a common parent) based on the elements they immediately follow.

For example, in the following situation

<p>The <strong>only</strong> police <em>officer</em> who may handle these forms is <a href="mailto:[email protected]">James Smith</a></p>

the <strong>, the <em>, and the <a> elements are all siblings, however, they are not all adjacent to one another:

In this situation you could use an adjacent sibling selector to select <em> elements when they immediately follow <strong> elements.

Syntax

An adjacent selector is formed by listing the elements that must be adjacent in the order in which they must appear. Elements are separated by a "+". Other selectors, for example class selectors can be used in an adjacent selector, as well as simple type selectors.

So, with our White House example above, the adjacent selector for selecting em elements adjacent to strong elements would be

strong + em {}

Use

This is another really useful selector because it requires no changes to the HTML. There are all sorts of formatting situations in which you might want to use it. For example you might want to apply a special style only to paragraphs that occur immediately after ordered lists.

ol + p {}