adjacent selectors

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 contextual selector selects any descendent 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:james@whitehouse.gov">James Smith</a></p>

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

  • <strong> and <em> are adjacent
  • <em> and <a> are adjacent
  • but <strong> and <a> are not adjacent

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 HTML element selectors.

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

strong + em

Use

Why have such a selector? Think of the following situation:

h1 {margin-top: 5mm;

margin-bottom: 5mm}

h2 {margin-top: 3mm;

margin-bottom: 3mm}

In the document which uses this style sheet, where an <h2> directly follows an <h1>, there will be extra space between them (compared with the situation where a paragraph follows an <h1>). In order to reduce the spacing, we could use an adjacent selector like this

h1 + h2 {margin-top: -3mm}

Browser support

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

next: attribute selectors