CSS Adjacent Sibling Selector

The adjacent sibling selector (Adjacent sibling selector) can select an element that immediately follows another element, and both have the same parent element.

Select Adjacent Siblings

If you need to select an element that immediately follows another element and both have the same parent element, you can use the adjacent sibling selector (Adjacent sibling selector).

For example, if you want to increase the top margin of the paragraph that immediately follows the h1 element, you can write it like this:

h1 + p {margin-top:50px;}

This selector is read as: 'Select the paragraph that immediately follows the h1 element, where both the h1 and p elements have the same parent element'.

Try It Yourself

Grammar Explanation

The adjacent sibling combinator used by the adjacent sibling selector is the plus sign (+).

Note:Like the child combinator, there can be whitespace characters next to the adjacent sibling combinator.

Please see the following document tree fragment:

<div>
  <ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
  </ul>
  <ol>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
  </ol>
</div>

In the above snippet, there are two lists within the div element: one unordered list and one ordered list, each containing three list items. These two lists are adjacent siblings, and the list items themselves are also adjacent siblings. However, the list items in the first list are not adjacent siblings with those in the second list because these two groups of list items do not belong to the same parent element (at most they can be considered cousins).

Remember, a combinator can only select the second element of two adjacent siblings. See the following selector:

li + li {font-weight:bold;}

The selector above will only make the second and third list items in the list bold. The first list item is not affected.

Try It Yourself

Combine with other selectors

The adjacent sibling combinator can also be combined with other combinators:

html > body table + ul {margin-top:20px;}

This selector is interpreted as: Select all brother ul elements that appear immediately after a table element, which is contained within a body element, and the body element itself is a child element of the html element.