Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

Subsequent-sibling combinator (~)

The selector A ~ B matches B elements that share a parent with an earlier A element. The elements do not need to be immediately adjacent.

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

Syntax

A ~ B { /* declarations */ }

The ~ combinator (tilde, U+007E) connects two compound selectors. In A ~ B, the letters represent selectors: an element B matches if it shares a parent with some earlier element A in the document tree.

Other elements may occur between A and B. The selector can match multiple later B elements, but does not select A itself, earlier siblings, or elements nested inside another sibling. Tree order matters, not visual placement.

Unlike A + B, which requires immediately adjacent elements, A ~ B allows intervening elements. In the example, h2 ~ p matches first and last; it does not match before or nested, because the latter has a different parent.

Examples

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Subsequent siblings</title>
<style>
  h2 ~ p { border-left: 4px solid blue; }
</style>
<section id="demo">
  <p id="before">Before</p>
  <h2>Heading</h2>
  <p id="first">First</p>
  <div><p id="nested">Nested</p></div>
  <p id="last">Last</p>
</section>
<pre id="result"></pre>
<script>
  const matches = document.querySelectorAll('#demo > h2 ~ p');
  document.getElementById('result').textContent =
    Array.from(matches, element => element.id).join(', ');
</script>
</html>

Result

first, last

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