Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

CSS :has Selector

CSS :has Selector

Complete CSS Selector Reference Manual Complete CSS Selector Reference Manual

Example

We want to apply styles to elements that contain

child .parent elements:

.parent

:has

(

div

)

{

border:

1

px

solid

red

;

}

Try it »


Definition and usage

The CSS :has pseudo-class is a selector that allows you to select an element based on its descendant elements.

The :has pseudo-class is very useful in CSS selectors because it can select elements based on more complex conditions.

  • :has This pseudo-class is a relatively new feature in CSS and may not be supported by all browsers. Before using it, it is recommended to check browser compatibility.
  • :has The pseudo-class cannot be used with * selectors; it can only be used with type selectors (such as div, span etc.) or class selectors.

Browser support

The numbers in the table indicate the first browser version that supports this property.

Selector
:invalid 10.0 10.0 4.0 5.0 10.0

CSS Syntax

parent:has(selector) {

    /* Style rules */

}

  • parent: the selector representing the parent element.
  • selector: the selector representing the child element you want to find within the parent element.

More examples

Select elements containing a specific class name

Example

If you want to select the parent element that contains a child element with the class name .active:

div

:has

(

.active

)

{

background-color:

yellow

;

}

Try it »

Select elements containing multiple specific child elements

Example

If you want to select a parent element that contains both

  • and
    child
      element:

      ul

      :has

      (

      li

      )

      :has

      (

      div

      )

      {

      border:

      2

      px

      dashed

      blue

      ;

      }

      Try it »

      The above code will add a blue dashed border to elements that contain both

    • and