Skip to main content

The Adjacent Sibling Combinator

We've explored selectors based on hierarchy (parent/child). Now we look at selectors based on sequenceβ€”elements that appear one after the other.

The Adjacent Sibling Combinator selects an element that is the immediate successor of a preceding element, and both must be at the same level in the HTML structure (siblings).

It is represented by the plus sign (+).


How to Use the Adjacent Sibling Combinator​

The rule is very strict: the second element must directly and immediately follow the first element in the HTML source code.

The Syntax​

Adjacent Sibling Combinator Syntax
preceding_selector + target_selector {
/* styles applied ONLY to the target_selector */
}
  • preceding_selector: The element that comes first (e.g., h2, .callout).
  • target_selector: The element that immediately follows the preceding element.

Example: Spacing After a Heading​

A very common use case is applying specific top margin or spacing to a paragraph only when it immediately follows a main heading.

<div class="content">
<h2>Main Section Title</h2> <p>First paragraph after the title.</p> <div>
<p>Second paragraph (UNSTYLED)</p>
</div>
</div>

In this example, the first paragraph gets the margin-top: 30px; because it is the adjacent sibling of <h2>. The second paragraph is ignored because it is contained within a <div>, meaning its immediate preceding sibling is the <div>, not the <h2>.


How it Relates to Flow​

The Adjacent Sibling Combinator is a powerful tool for controlling the vertical flow of a document without relying on classes.

Strict Sequential Requirement​

Remember this rule: there can be no other element or even a comment node between the two siblings.

HTML SequenceCSS Rule: h2 + pResult
<h2>...</h2> <p>...</p>βœ… MatchThe paragraph is styled.
<h2>...</h2> <div>...</div> <p>...</p>No MatchThe <div> breaks the adjacency.
<h2>...</h2> <p>...</p>No MatchThe comment node technically breaks the adjacency.

Interactive Adjacent Sibling Demo​

In this demo, the CSS rule targets a list item (<li>) that immediately follows an element with the class .header-item.

Challenge: Try adding a new empty <li></li> between "Item A" and "Item B" in the HTML panel. What happens to the styling of "Item B"?