Selector - has pseudo class (hierarchical condition)

About

:has() is a logical pseudo-class that takes a relative selector list as an argument and return a Boolean. It's a predicate expression.

It works for now only on safari

Tree

has predicate operates on the tree (descendant/ascendant), not on the selected element.

If you want to select an element that has the class a and b uses a concatenation expression

.a.b { }

Example of selectors

Matches elements that contains other elements

  • matches only a elements that contain an img child:
a:has(> img){
  color: red;
}
<a href="#"><img src="/_media/lenna.png" width="200px"/> Lenna</a>

Matches elements that have a next sibling

  • matches a dt element immediately followed by another dt element (ie sibling)
dt:has(+ dt)

Matches element that does not contain

section:not(:has(h1, h2, h3, h4, h5, h6))

Ordering matter

  • Note that ordering matters in the above selector. Swapping the nesting of the two pseudo-classes would result matching any <section> element which contains anything that’s not a heading element.
section:has(:not(h1, h2, h3, h4, h5, h6))

5 or more children

Make a list of 5 or more children a flat list.

ul:has(:nth-child(n+5)) li {
  display: inline;
}

Adds semi-colon after each item in a list excepts last one

Add a separator except to the last one.

ul:has(:nth-child(n+5)) li:not(:last-child)::after {
  content: ';';
}

where:


Powered by ComboStrap