Sub topic 2
How :has() Is Written
This chapter covers the grammar of :has(): what goes inside the parentheses, how the browser reads it, and which mistakes change the meaning of a rule. It assumes you know basic selectors (type, class, ID, attribute), the four combinators (descendant, >, +, ~), pseudo-classes such as :hover and :nth-child(), and the basics of specificity. The previous chapter explained why a relational selector is useful. Here the focus is on writing one correctly.
The basic shape
:has() is a functional pseudo-class. It goes after a selector and takes a list of arguments in parentheses.
.card:has(img) {
display: grid;
grid-template-columns: 200px 1fr;
gap: 1rem;
}This rule has two parts:
- The anchor is everything before
:has(). Here it is.card. It decides which element the declarations apply to. - The condition is the argument inside the parentheses. Here it is
img. It decides whether the anchor qualifies.
The rule styles the anchor, never the element found by the condition. A .card that contains an <img> gets the grid layout. The image itself is not touched. This is why :has() lets you style a parent: you write the parent as the anchor and describe the child in the condition.
If you leave out the anchor, as in :has(img) { }, the anchor is an implicit universal selector. The rule then matches every element that contains an image, including html and body. Write the anchor explicitly unless you really want that.
Relative selectors
The argument of :has() is not an ordinary selector. It is a relative selector. That is a selector that starts from the anchor and describes a relationship to it. The anchor acts as the starting point, and the argument describes where to look from there.
When the argument has no leading combinator, the relationship is "descendant". So .card:has(img) reads as "a .card that has an img somewhere inside it, at any depth". The img can be a child, a grandchild, or deeper.
To change the relationship, put a combinator at the very start of the argument.
| Argument | Reads as | Where the browser looks |
|---|---|---|
| `:has(img)` | has an `img` descendant | Anywhere inside the anchor |
| `:has(> img)` | has an `img` child | Direct children only |
| `:has(+ p)` | is immediately followed by a `p` | The next sibling only |
| `:has(~ p)` | is followed later by a `p` | Any later sibling |
Here is the child combinator in a rule:
figure:has(> figcaption) {
border-bottom: 2px solid currentColor;
}Given the markup below, the first figure matches and the second does not.
<figure>
<img src="a.jpg" alt="A lake">
<figcaption>A lake at dawn</figcaption>
</figure>
<figure>
<div>
<img src="b.jpg" alt="A hill">
<figcaption>A hill at noon</figcaption>
</div>
</figure>In the second figure, the figcaption is a grandchild, not a direct child. figure:has(figcaption) without the > would match both. Choose between the two forms deliberately. The plain form is more forgiving of markup changes. The > form is more precise and is also cheaper for the browser to check.
The sibling combinators point forward in the document. This is how :has() selects an earlier sibling:
h2:has(+ p) {
margin-block-end: 0.25rem;
}
h2:has(~ ul) {
color: rebeccapurple;
}The first rule styles an h2 whose next sibling is a p. The second styles an h2 that has a ul anywhere after it among its siblings. Both styles land on the h2, which comes before the element it tests for. The next chapters cover sibling matching in more detail.
How the browser reads a match
For each candidate element, the browser works through the same steps. This diagram shows the order.
Two details follow from this:
- The anchor is checked first. Its cost and its meaning are independent of what is inside
:has(). - The condition only asks whether at least one element exists. It does not matter whether one image or ten are found, so
:has()cannot count matches. Counting needs a trick covered in a later chapter.
Lists, compounds, and chains
The argument can contain more than a single simple selector. How you combine pieces decides whether you get "or" or "and".
A comma means "or"
The argument is a selector list, and each item in it is a separate relative selector. The anchor matches if any item matches.
.card:has(img, video, iframe) {
padding: 0;
}This matches a card that contains an image, a video, or an iframe. Each item can have its own combinator:
.item:has(> img, + .item) {
margin-block: 1rem;
}Here > img looks inside the anchor and + .item looks at the next sibling. The two items test different relationships, and either one is enough.
A compound means "and" on one element
A compound selector inside the argument must be satisfied by a single element.
.card:has(img.hero) { }This needs one element that is both an img and has the class hero. A card with a plain img and a separate div.hero does not match.
Chaining `:has()` means "and" on different elements
To require two independent conditions, repeat :has() on the anchor:
.card:has(img):has(h2) {
border: 1px solid #ccc;
}This matches a card that contains an image and also contains an h2. They can be different elements anywhere inside. Compare it with .card:has(img, h2), which needs only one of them.
Complex selectors inside the argument
You can also write a multi-part relative selector:
section:has(> h2 + p) {
gap: 0.5rem;
}This matches a section with a direct child h2 that is immediately followed by a p. The leading > applies to the h2. The + p then continues from that h2.
Where :has() can sit in a selector
:has() is an ordinary pseudo-class, so it can appear anywhere a pseudo-class can. What comes after it applies to elements inside the anchor.
.card:has(img) p {
color: #444;
}This styles paragraphs inside cards that contain an image. The p is the subject of the rule, and :has() only filters which cards qualify. The subject of a selector is the last compound selector, and that is the element that receives the styles.
Compare these two rules:
.card:has(img) { } /* styles the card */
.card img { } /* styles the image */The first puts :has() in the subject, so the card is styled. The second styles the image. Before you write the declarations, say aloud which element should receive them. That tells you where :has() belongs.
Invalid arguments
The :has() argument list is unforgiving. If any item in the list is invalid, the whole selector is invalid and the browser drops the entire rule.
/* Invalid: "!!" is not a selector. The whole rule is ignored. */
.card:has(img, !!) {
display: grid;
}An unknown tag name is fine, because it is valid syntax that matches nothing. A typo in syntax, such as a stray symbol, is not fine. Some other selector lists skip bad items and keep the rest. :has() does not. When a :has() rule has no effect at all, check the syntax of every item first.
Common mistakes
- Putting a combinator in the wrong place. The combinator belongs inside the parentheses.
.card >:has(img)and.card:has(> img)mean very different things. The first selects a:has()match that is a direct child of.card. The second selects a.cardthat has animgchild. - Expecting the argument element to be styled.
.card:has(img)never styles the image. Add a descendant selector after it,.card:has(img) img, if you also want to style the image. - Mixing up "or" and "and". Commas inside one
:has()give "or". Several:has()pseudo-classes in a row give "and". - Using
:has()without an anchor. A bare:has(img)matcheshtml,body, and every other ancestor of an image. This can restyle large parts of the page. - Forgetting that the default is descendant. If a rule fires on a card whose image is deep in a nested
div, the missing>is the likely cause.
The prerequisite list above mentions specificity, and :has() has its own rule for it. A later chapter covers that rule. For now, remember that the arguments inside :has() count toward the final specificity of the selector, so a rule with an ID in its argument is heavier than it looks.
Summary of the grammar
anchor:has(relative-selector-list)styles the anchor.- A relative selector may start with
>,+, or~. With no leading combinator it means "descendant". - Commas give "or". A compound selector means "same element". Repeated
:has()gives "and across elements". :has()tests existence only. It does not count matches.- One invalid item in the list invalidates the rule.
Exercise
Given this markup, which of the three selectors match the ul? (a) ul:has(> li), (b) ul:has(> a), (c) ul:has(a).
<ul>
<li><a href="/home">Home</a></li>
</ul>
Show answer
Selectors (a) and (c) match. The li is a direct child of the ul, so (a) matches. The a is a grandchild, so (b) fails because > allows direct children only. Selector (c) has no combinator, so it means "descendant" and finds the a at any depth.
Exercise
Write one rule that gives a .panel a yellow background (background: yellow) if it contains both a button and a textarea. Then explain how your rule would change if you used a comma-separated list instead.
Show answer
Use .panel:has(button):has(textarea) { background: yellow; }. Chaining two :has() pseudo-classes requires both conditions. With .panel:has(button, textarea), the comma means "or", so a panel with only a button, or only a textarea, would also match.