Sub topic 3
Styling by Number of Children with `:has()`
Assume you know basic selectors, combinators, pseudo-classes, the cascade, and specificity. This chapter uses :has() to select an element from its contents or later siblings.
Styling by number of children
:has() can act as a quantity query. Select a list only when its fourth direct child exists:
ul:has(> li:nth-child(4)) {
columns: 2;
}The > means that only direct li children count. A fifth or later item also satisfies the condition because a fourth item exists.
Putting it together: cards, forms, and a theme toggle
Content-aware cards can change layout when they contain an image:
.card:has(img) {
display: grid;
grid-template-columns: 200px 1fr;
gap: 1rem;
}
.field:has(input:focus-visible) {
outline: 2px solid royalblue;
}
.field:has(input:invalid:not(:placeholder-shown)) label {
color: crimson;
}A page can also react to a checked control without JavaScript:
<label><input type="checkbox" id="dark-toggle"> Dark mode</label>
<main>Page content</main>:root:has(#dark-toggle:checked) {
color-scheme: dark;
}What `:has()` cannot do
Do not nest :has() inside another :has(). Pseudo-elements such as ::before and ::after cannot normally be used as its argument. Keep conditions explicit instead of trying to build deeply recursive selectors.
Keeping `:has()` selectors fast
Scope relational selectors to a useful component, such as .card:has(img), rather than applying broad conditions to every element. Prefer direct-child checks when descendants are unnecessary. Avoid long chains and selectors that inspect large parts of the document repeatedly.
> callout tip > A selector such as ul:has(> li:nth-child(4)) is clearer and usually cheaper to evaluate than a broad selector that searches every descendant.
Browser support and graceful fallbacks
Put enhanced rules inside a feature query and define a usable base style first:
.card {
padding: 1rem;
}
@supports selector(:has(*)) {
.card:has(img) {
display: grid;
}
}Using `:has()` from JavaScript
Selector APIs accept :has() where the browser supports it:
const sections = document.querySelectorAll("section:has(> h2)");
const card = document.querySelector(".item");
const isCardWithImage = card?.matches(":has(img)") ?? false;Unsupported or invalid selector syntax can throw a SyntaxError, so use feature detection or a fallback when older browsers matter.
Exercise
Which selector matches a ul with at least four direct li children?
Show answer
ul:has(> li:nth-child(4)).