Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Pseudo-classes

The :has() pseudo-class

Reference for the CSS :has() relational pseudo-class: style an element based on its children, following siblings or state, with relative selectors and live examples.

The :has() pseudo-class is the relational selector. It matches an element if at least one relative selector in its argument list matches, anchored at that element. The most famous use is as a "parent selector": .card:has(img) is a card that contains an image.

Because the argument can start with a combinator, :has() can also look at following siblings: h2:has(+ p) is a heading directly followed by a paragraph. The state of a form control can restyle its whole group with label:has(input:checked).

CSS
.field:has(input:invalid) {
  border-color: crimson;
}

Try it

Style the parent by its content

Syntax

CSS
:has( <relative-selector-list> ) { }

/* relative selectors may start with a combinator */
/*   :has(img)          descendant (default) */
/*   :has(> img)        direct child         */
/*   :has(+ p)          next sibling         */
/*   :has(~ p)          any later sibling    */
  • Specificity: equal to the most specific selector in its argument list.
  • Restrictions: :has() cannot be nested inside another :has(), and pseudo-elements are not allowed in the argument.
  • Parsing: the list is not forgiving; one invalid selector invalidates the rule.

Values

Syntax and arguments Description
:has(img) Has an img descendant.
:has(> img) Has an img as a direct child.
:has(+ p) Is immediately followed by a p sibling.
:has(~ .x) Is followed later by a sibling .x.
:has(a, b) Matches if either relative selector matches.
:not(:has(img)) Has no image.
:has(:focus-visible) Has a focused descendant, like :focus-within with more control.

Usage notes

  • Combine with state. form:has(:invalid), body:has(dialog[open]) (to stop scrolling) and .menu:has(:hover) open up UI states that once needed JavaScript.
  • Be specific on the left. :has() alone, or div:has(p) on a huge document, forces the browser to check many elements. Anchor it to a class and keep the argument short.
  • Quantity logic. ul:has(li:nth-child(4)) means "has at least four items". Combine with :not() for "at most three".
  • Previous siblings. :has() can select elements before another: li:has(+ li.active) is the item just before the active one.
  • Specificity is inherited from its argument. a:has(.icon) counts as a plus .icon.
  • Layout feedback loops. Avoid conditions that depend on a size changed by the rule itself.
  • Progressive enhancement. Use @supports selector(:has(a)) to provide a fallback.

Browser support

Baseline since December 2023 (Chrome and Edge 105, Safari 15.4, Firefox 121).