CSS :has() Selector

❮ Previous Selectors Next ❯

Example

body:has(h1, p) {
  background: red;
}

Meaning

The :has() selector represents an element if any of the relative selectors that are passed as an argument match at least one element when anchored against this element.

This pseudo-class presents a way of selecting a parent element or a previous sibling element with respect to a reference element by taking a relative selector list as an argument.

The :has() pseudo-class takes on the specificity of the most specific selector in its arguments the same way as :is() and :not() do.

Note: The :has() pseudo-class cannot be nested within another :has(). This is because many pseudo-elements exist conditionally based on the styling of their ancestors and allowing these to be queried by :has() can introduce cyclic querying.

Version: CSS3




Standard Syntax

:has(relativeSelectorList) {
  css declarations;
}



Browser Support

The numbers in the table specify the first browser version that fully supports the property.




Status







Relative Selector List

A relative selector list is a comma-separated selector list parsed as relative selectors, which begin with an explicit or implied combinator.

h2:has(+ p, + ul.red) {
  font-style: italic;
}

In the above example, the italic style will be applied to any h2 heading that is immediately followed by <p> or <ul class="red">.

Note: That pseudo-elements and the :has() selector are not valid within the :has() relative selector list.

❮ Previous Selectors Next ❯