Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

Next-sibling combinator (+)

The selector A + B matches an element B immediately preceded by an element A with the same parent. Whitespace, text, and comments between the elements do not break this adjacency.

Version: CSS modules; structured CSSWG indexes reconciled with pinned MDN BCD; Chromium 152 scope gate, per-example verification still required

Syntax

A + B

The + combinator joins two selectors. In A + B, the letters stand for selectors, and the matched element is B, not A. Both elements must share a parent, and A must be the immediately preceding element sibling of B.

Adjacency checks ignore non-element nodes, including text, whitespace, and comments. Another element between A and B prevents that pair from matching. Document-tree order matters, not visual placement on the page.

In the example, h2 + p matches only #first. The preceding element of #second is a p, and that of #third is a span. Consequently, only #first receives a yellow background; the other paragraphs have white backgrounds.

Unlike A ~ B, A + B requires immediate adjacency. In contrast, A > B describes a parent–child relationship. Spaces around + are optional: h2+p and h2 + p mean the same thing.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Next-sibling example</title>
<style>
  p { background-color: rgb(255, 255, 255); }
  h2 + p { background-color: rgb(255, 255, 0); }
</style>
<section>
  <h2>Heading</h2>
  <!-- Comments and whitespace do not break adjacency. -->
  <p id="first">First paragraph</p>
  <p id="second">Second paragraph</p>
  <h2>Another heading</h2>
  <span>Intervening element</span>
  <p id="third">Third paragraph</p>
</section>
</html>

Result

#first: rgb(255, 255, 0)
#second: rgb(255, 255, 255)
#third: rgb(255, 255, 255)

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources