CSS :hasSelectors

Complete CSS Selector Reference Manual

Example

We want to apply styles to the containing<div>Sub-element's.parentelement:

.parent:has(div) { border: 1px solid red; }

Try it Yourself »

Definition and use

The :has pseudo-class in CSS 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 allows you to select elements based on more complex conditions.

  • :hasThe 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.
  • :hasPseudo-classes cannot be*Used together with selectors, it can only be used with type selectors (such asdiv、spanetc.) or used together with class selectors.

Browser Support

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

Selectors
:invalid 10.0 10.0 4.0 5.0 10.0

CSS Syntax

parent:has(selector) {
    /* 样式规则 */
}
  • parent: Indicates the selector of the parent element.
  • selector: Indicates the selector for the child element you wish to find in the parent element.

More Examples

Select elements containing a specific class name

Example

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

div:has(.active) { background-color: yellow; }

Try it Yourself »

Select elements containing multiple specific child elements

Example

If you want to select elements that simultaneously contain<li>and<div>Sub-element's<ul>element:

ul:has(li):has(div) { border: 2px dashed blue; }

Try it Yourself »

The above code will add a blue dashed border to elements that simultaneously contain<li>and<div>Sub-element's<ul>Add a blue dashed border to elements.


Complete CSS Selector Reference Manual

other extensions