...

/

An Introduction to the :has() Selector

An Introduction to the :has() Selector

Learn about :has(), a CSS pseudo-class for styling elements based on descendant conditions, offering versatility from simple child relationships to complex scenarios.

Working of the :has() selector

To get a feel for how :has() works, let’s look at an example of how to apply it. In the following selector, we’re testing if an <article> element has an <img> element as a child:

Press + to interact
article:has(img) {}

The image below shows a possible result of this selector. Three article elements are shown, two of which contain images, both with a pale green background and different padding from the one without an image.

Press + to interact
Styling articles containing images using the :has() selector
Styling articles containing images using the :has() selector

The selector above will apply as long as an <img> element exists anywhere with the <article> element—whether as a direct child or as a descendant of other nested elements.

If we want to make sure the rule applies only if <img> is a direct (unnested) child of the <article> element, we can also include the child combinator:

Press + to interact
article:has(> img) {}
...