MDN self-hosted library · e01.org

Subsequent-sibling combinator

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

css
img ~ p {
  color: red;
}
html
<article>
  <span>This is not red because it appears before any paragraph.</span>
  <p>Here is a paragraph.</p>
  <code>Here is some code.</code>
  <span>
    This span is red because it appears after the paragraph, even though there
    are other nodes in between.
  </span>
  <p>Whatever it may be, keep smiling.</p>
  <h1>Dream big</h1>
  <span>
    Doesn't matter how many or what kind of nodes are in between, all spans from
    the same parent after a paragraph are red.
  </span>
</article>
<span>
  This span is not red because it doesn't share a parent with a paragraph.
</span>
css
p ~ span {
  color: red;
}
html
<h1>Dream big</h1>
<span>And yet again this is a red span!</span>
<div class="foo">
  <p>Here is another paragraph.</p>
  <span>A blue span</span>
  <div class="foo">
    <span>A green span</span>
  </div>
</div>
css
.foo p ~ span {
  color: blue;
}

.foo p ~ .foo span {
  color: green;
}