Selecting siblings

As in the definitions of child and descendant selectors, in the definitions below, one and two are both selectors, which means that they can be tag names, class values, ID values, or combined selectors.

For the examples, suppose we have the following elements in the body element:

<article>
  <header class="top">Important news!</header>
  <p class="odd">One</p>
  <p id="second">Two</p>
  <p class="odd">Three</p>
  <p>Four</p>
</article>

Next sibling selectors

A next sibling selector is of the form one + two. It specifies a rule that applies to any element selected by two which is the next siblingA sibling of a node x is a node with the same parent as x. of an element selected by one.

The following examples specify which paragraphs will be styled by the rule using the given selector.

Selector Paragraphs styled
.top + p One
.odd + p Two and Four
p#second + p Three

To understand why:

  • For the first example, we figure out which elements are chosen by .top (just the header element). Then, we select a next sibling of a chosen element if it is a paragraph element.
  • For the second example, we figure out which elements are chosen by .odd (paragraphs One and Three). Then, we select a next sibling of a chosen element if it is a paragraph element. Since the next siblings of paragraphs One and Three are both paragraph elements, both are included.
  • For the third example, we figure out which elements are chosen by p#second (just paragraph Two). Then, we select a next sibling of a chosen element if it is a paragraph element.

General sibling selectors

A general sibling selector is of the form one ~ two. It specifies a rule that applies to any element selected by two which is a following siblingA sibling of a node x is a node with the same parent as x. of an element selected by one.

The following examples specify which paragraphs will be styled by the rule using the given selector.

Selector Paragraphs styled
.top ~ p One, Two, Three, and Four
.top ~ p.odd One and Three
.odd ~ p Two, Three, and Four

To understand why:

  • For the first example, we figure out which elements are chosen by .top (just the header element). Then, we select a following sibling of a chosen element if it is a paragraph element.
  • For the second example, we figure out which following siblings of the header element are paragraph elements in the class odd.
  • For the third example, we figure out which elements are chosen by .odd (paragraphs One and Three). Then, we select a following sibling of a chosen element if it is a paragraph element. The result follows from the fact that Two, Three, and Four all follow One and Four follows Three. (We list any element that has been selected at least once. Here Four has been selected twice.)