Sub topic 3
Matching descendants and direct children
This chapter covers the two most common uses of :has(): checking whether an element contains something at any depth, and checking whether it contains something as a direct child. It assumes you know basic selectors, the descendant (space) and child (>) combinators, and the idea that a selector's rightmost compound selector is the element that gets styled. Sibling forms of :has() and specificity come in later chapters.
The anchor and the argument
A selector with :has() has two parts:
- The anchor is the element the rule styles. It is whatever the selector matches before
:has()is applied. - The argument is the relative selector list inside the parentheses. It is evaluated starting from the anchor.
The anchor matches only if the argument finds at least one element. The argument never becomes the styled target. If you write .card:has(img), the .card gets the declarations, not the image.
Matching a descendant at any depth
With no combinator at the start, the argument is treated as a descendant search. :has(img) means "has an img somewhere inside it", which is the same as the .card img relationship read from the other direction.
.card:has(img) {
display: grid;
grid-template-columns: 200px 1fr;
gap: 1rem;
}This rule matches a .card that contains an img as a child, a grandchild, or deeper. A card with no image keeps its normal block layout. Before :has(), you needed a modifier class such as .card--with-image, added by hand or by JavaScript. Now the markup stays the same and the CSS reacts to its content.
The following HTML shows the "any depth" behavior. All three cards match .card:has(img).
<article class="card"><img src="a.jpg" alt="A"><p>Direct child image</p></article>
<article class="card"><div class="media"><img src="b.jpg" alt="B"></div><p>Grandchild image</p></article>
<article class="card"><div><div><a href="/x"><img src="c.jpg" alt="C"></a></div></div><p>Deeply nested image</p></article>An implicit leading descendant combinator is the rule. :has(img) and :has(.media img) are both valid. In the second, .media must be inside the anchor and img must be inside that .media. Both elements have to be within the anchor, so .card:has(.media img) will not match a card where .media is an ancestor of the card.
Restricting to direct children with `>`
Start the argument with the child combinator to require a direct child.
figure:has(> figcaption) {
border-bottom: 2px solid currentColor;
}This matches a figure whose own child is a figcaption. A figcaption buried in a nested figure does not count. In relative selectors, the leading > is allowed because the selector is relative to the anchor. Outside :has(), a selector cannot start with >.
The difference matters when elements can nest. Consider this markup.
<figure class="outer">
<img src="outer.jpg" alt="Outer">
<figure class="inner">
<img src="inner.jpg" alt="Inner">
<figcaption>Inner caption</figcaption>
</figure>
</figure>figure:has(figcaption)matches both.outerand.inner, because the caption is a descendant of both.figure:has(> figcaption)matches only.inner, because only it has afigcaptionas a direct child.
If you mean "this element's own caption", use >. If you mean "anywhere inside", leave it out.
A complete working example
This page runs as written. Open it in a current browser and only the first card gets the two-column layout.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>:has() cards</title>
<style>
.card {
border: 1px solid #ccc;
padding: 1rem;
margin-block: 1rem;
max-width: 40rem;
}
.card:has(img) {
display: grid;
grid-template-columns: 120px 1fr;
gap: 1rem;
}
.card:has(> h2) {
background: #f7f7ff;
}
.card img {
width: 100%;
height: auto;
}
</style>
</head>
<body>
<article class="card">
<img src="https://placehold.co/120x80" alt="Placeholder">
<div>
<h2>With image</h2>
<p>This card has an image, so it uses a grid.</p>
</div>
</article>
<article class="card">
<h2>Without image</h2>
<p>This card has no image, so it stays a plain block.</p>
</article>
</body>
</html>The first card has no direct h2 child, because the heading is inside a div. It therefore does not get the tinted background, while the second card does. That result confuses many people the first time, and it shows why choosing between :has(h2) and :has(> h2) is a real decision.
Combining conditions
Commas and chained pseudo-classes give you OR and AND.
- A comma inside the argument is OR:
.card:has(img, video)matches a card that contains animgor avideo. - Chaining two
:has()pseudo-classes is AND:.card:has(img):has(figcaption)requires both, but they can be in different places inside the card. - A compound inside the argument is a single-element test:
.card:has(img.hero)requires one element that is both animgand has the classhero.
Do not confuse the last two. .card:has(img):has(.hero) is satisfied by an img in one place and a different element with .hero somewhere else. .card:has(img.hero) requires one element to be both.
You can also style an element inside the matched anchor, by continuing the selector after :has().
.card:has(> img) h2 {
font-size: 1.25rem;
}This styles an h2 that is a descendant of a card that has a direct img child. The h2 is the subject here. The :has() test is only a condition on its ancestor.
`:not(:has())` versus `:has(:not())`
These two look similar and mean different things.
.card:not(:has(img)) {
padding: 2rem;
}
.card:has(:not(img)) {
border: 1px solid #ccc;
}.card:not(:has(img))matches a card that contains noimganywhere inside it. This is the correct way to say "cards without images"..card:has(:not(img))matches a card that contains at least one descendant element that is not animg. A card with an image and a paragraph matches, because the paragraph is not an image.
A card with only an image inside it does not match the second rule, and an empty card does not match it either. Reach for :not(:has(...)) when you want to negate the whole condition. The next chapters expand on combining :has() with :not() and :is().
Edge cases and common errors
- Only elements count.
:has()tests element nodes. Apcontaining only text does not match:has(:not(img)), because it has no child element, and:has()cannot test text content. To test whether an element has no children at all, including text, use:empty. - Styling the wrong thing. The subject is to the left of
:has(). If the image should change, write.card imgor.card:has(img) img, not.card:has(img). - Forgetting
>with nested components. If a.cardcan contain another.card,.card:has(img)matches the outer card whenever an inner card has an image. Use.card:has(> img)when you need the card's own image, and add a wrapper selector when images sit inside a known wrapper, such as.card:has(> .media img). - Treating
:has()as a live query that ignores the cascade. It re-evaluates when the DOM or state changes, but it is only a condition. It does not change which element gets styled. - Assuming the argument can be a pseudo-element.
.card:has(::before)is not valid, which a later chapter covers. - Using
:has()inside:has(). Nesting:has()in:has()is not allowed. Chain two:has()calls on the anchor instead, as in.card:has(img):has(figcaption).
A quick decision guide
| You want to match | Selector | Why |
|---|---|---|
| Containers with an image anywhere inside | `.card:has(img)` | Implicit descendant search. |
| Containers whose own child is a caption | `figure:has(> figcaption)` | `>` limits the test to direct children. |
| Containers with an image or a video | `.card:has(img, video)` | A comma means OR. |
| Containers with both an image and a caption | `.card:has(img):has(figcaption)` | Two chained `:has()` mean AND. |
| Containers with no image anywhere | `.card:not(:has(img))` | Negates the whole test. |
Checking the work
You can verify a selector in the browser console without editing any CSS. For example, document.querySelectorAll('.card:has(> h2)') returns the cards with a direct heading child. The JavaScript chapter covers this in more detail.
Exercise
A page has <div class="panel"><section><h3>Title</h3></section></div>. Which of these match the .panel: .panel:has(h3), .panel:has(> h3), .panel:has(> section > h3)? Explain each result.
Show answer
.panel:has(h3) matches, because h3 is a descendant at any depth. .panel:has(> h3) does not match, because the h3 is a grandchild, not a direct child. .panel:has(> section > h3) matches, because it requires a direct section child that itself has a direct h3 child, and both exist.
Exercise
You want to give extra padding to every .card that contains no img at any depth. A teammate writes .card:has(:not(img)) { padding: 2rem; }. Why is this wrong, and what is the correct selector?
Show answer
:has(:not(img)) matches any card with at least one descendant element that is not an img, so a card with an image and a paragraph also matches, and a card with only an image does not. The correct selector is .card:not(:has(img)), which negates the whole test and matches cards that contain no image anywhere.