CSS combinatorSelectors

A ~ B

The ~ sign selects every B element that comes anywhere after element A and shares the same parent.

On this page

Example

#
CSS
.hint {
  display: none;
}

.field input:focus ~ .hint {
  display: block;
}
Preview

Click the field. The hint sits two elements further along, and ~ still finds it. The + combinator wouldn’t work here.

Definition and usage

#

The subsequent-sibling combinator, also called the general sibling combinator, is a looser version of +. The notation h2 ~ p selects every paragraph that comes after an h2 heading at the same level, even if other elements sit between them.

Just like with +, only elements after A count, never before it, and only ones that share the same parent. An element in a different container doesn’t match, even if it sits lower in the code.

The combinator comes in handy in interfaces driven by a form field’s state: a field at the start of a container can change the look of elements further along within the same parent, for example input:focus ~ .hint. These days, similar effects are often easier to write with :has(), which doesn’t depend on the order of elements.

Syntax

#
Syntax
A ~ B { property: value; }

Example selectors

#
  • .start ~ span

    Every span after .start, including the 5 that comes after the em element. The 1 drops out, because it sits before .start.
  • .start ~ *

    All of .start’s subsequent siblings, regardless of element type.
  • span ~ span

    Every span that has another span somewhere before it. All of them match except the first.

Example selectors in practice

#

.start ~ span

Every span after .start, including the 5 that comes after the em element. The 1 drops out, because it sits before .start.
.start ~ span { background: #7c3aed; color: #fff; }

.start ~ *

All of .start’s subsequent siblings, regardless of element type.
.start ~ * { background: #7c3aed; color: #fff; }

span ~ span

Every span that has another span somewhere before it. All of them match except the first.
span ~ span { background: #7c3aed; color: #fff; }

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • The combinator doesn’t see elements before A or in other containers. If something isn’t working, check in dev tools whether both elements share the same parent.
  • The trick with a hidden checkbox and ~ lets you build a menu with no JavaScript, but for menus and accordions the <details> element or a button with aria-expanded is a better choice, since screen readers understand them.
  • :has() frees you from the ordering: .field:has(input:focus) .hint shows the hint no matter where it sits in the container.

Related entries

#

Spotted a mistake or missing an example? Write to us.