Sub topic 9
Putting it together: cards, forms, and a theme toggle
This chapter combines the pieces from earlier chapters into three working patterns: a content-aware card, a form field that reacts to its input, and a page-level dark mode switch. I assume you can write :has() with a relative selector, know the four combinators, and understand the basics of specificity. Each pattern follows the same recipe: pick the element you want to style, then describe the condition inside it or after it.
The shared recipe
Every pattern here has three parts.
- The subject is the element that gets styled. It is the part of the selector outside
:has(). - The condition is the relative selector inside
:has(). It describes something the subject contains or precedes. - The declarations are the styles applied when the condition holds.
The browser re-evaluates the condition when the DOM or element state changes, so none of these patterns needs JavaScript.
Pattern 1: content-aware cards
A card component often appears with and without an image. Without :has(), you add a modifier class such as .card--with-image in the markup. With :has(), the card reads its own contents.
<article class="card">
<img src="photo.jpg" alt="A mountain lake at dawn">
<div>
<h3>Mountain lake</h3>
<p>A short description of the place.</p>
</div>
</article>
<article class="card">
<div>
<h3>No photo here</h3>
<p>This card has text only.</p>
</div>
</article>.card {
border: 1px solid #ccc;
border-radius: 0.5rem;
padding: 1rem;
}
.card:has(img) {
display: grid;
grid-template-columns: 200px 1fr;
gap: 1rem;
}
.card img {
width: 100%;
height: auto;
}
.card:not(:has(img)) {
padding: 2rem;
}The first card becomes a two-column grid because it contains an img at any depth. The second card gets extra padding because it contains none.
Choosing between descendant and child matching
.card:has(img) matches if an image appears anywhere inside the card, including inside a nested component. If a card can hold another card, that can style the outer card by mistake. Restrict the match with the child combinator:
.card:has(> img) {
display: grid;
grid-template-columns: 200px 1fr;
}Now only a direct img child counts. Use the descendant form when you want any image to count, and the child form when the structure is fixed.
Not-has versus has-not
These two selectors look similar but test different things:
| Selector | Matches a card when |
|---|---|
| `.card:not(:has(img))` | The card contains no `img` at all |
| `.card:has(:not(img))` | The card contains at least one descendant that is not an `img` |
A card with an image and a heading matches the second selector, because the heading is not an image. For "has no image", always write :not(:has(img)).
Headings and captions
The same idea works for figures. A figure gets a rule only when it has a caption:
figure:has(> figcaption) {
border-bottom: 2px solid currentColor;
}Use the same pattern for any optional child: a card with a footer, a list item with a badge, an alert with an icon.
Pattern 2: form fields that react to their input
Form styling is where :has() helps most. The label and the input are siblings, but you often want to style the wrapper, the label, or the whole form based on the input's state. Selecting the wrapper from the input is a parent selection, so :has() is the right tool.
<form>
<div class="field">
<label for="email">Email</label>
<input id="email" type="email" required placeholder=" ">
</div>
<div class="field">
<label for="name">Name</label>
<input id="name" type="text" required placeholder=" ">
</div>
<button type="submit">Send</button>
</form>.field {
display: grid;
gap: 0.25rem;
margin-block-end: 1rem;
}
.field:has(input:focus-visible) {
outline: 2px solid royalblue;
}
.field:has(input:invalid:not(:placeholder-shown)) label {
color: crimson;
}
.field:has(input:valid:not(:placeholder-shown)) label {
color: seagreen;
}Three details matter here.
:focus-visiblehighlights the wrapper for keyboard focus, and usually not for mouse clicks, so the outline does not flash on every click.:placeholder-shownmatches only while the placeholder is visible, which means the input is empty. Combined with:invalid, it prevents an empty required field from showing an error before the user has typed anything.:placeholder-shownneeds aplaceholderattribute to exist. A single space,placeholder=" ", is enough when you do not want visible placeholder text. Without the attribute, the selector never matches, and the error styling would show nothing.
Form-level state
The same technique works one level up. The form can react when any field is invalid:
form:has(:invalid) button[type="submit"] {
opacity: 0.5;
}This makes the button look dim while the form is incomplete. It is only visual. The button still works and still receives focus, so keep real validation in the browser's built-in constraint checks or in your own code.
Required markers
You can also add a marker to the label of any field that contains a required input. The ::after pseudo-element sits on the label, outside the :has() argument, so this is allowed:
.field:has(input:required) label::after {
content: " *";
color: crimson;
}Pattern 3: a theme toggle with no JavaScript
The :root element, which is <html>, can use :has() to look at the whole page. If a checkbox is checked, the root matches and can change the color scheme for everything below it.
<label><input type="checkbox" id="dark-toggle"> Dark mode</label>
<main>Page content</main>A minimal version uses a single declaration:
:root:has(#dark-toggle:checked) {
color-scheme: dark;
}color-scheme: dark switches the browser's default colors for the page background, text, and form controls. For a custom palette, use custom properties on the root, so the whole page can read them:
:root {
--bg: #ffffff;
--fg: #1a1a1a;
--accent: royalblue;
}
:root:has(#dark-toggle:checked) {
color-scheme: dark;
--bg: #121212;
--fg: #eeeeee;
--accent: lightskyblue;
}
body {
background: var(--bg);
color: var(--fg);
}
a {
color: var(--accent);
}Because the checkbox does not need to be a parent or a sibling of the content, it can sit anywhere in the document. The root's :has() finds it at any depth.
Limits of the toggle
- The checked state is not saved. Browsers may restore form state on back navigation or reload, but you cannot rely on it. To persist the choice, store it with JavaScript, for example in
localStorage, and set the checkbox'scheckedproperty on load. - The toggle follows no system preference by default. You can combine it with
@media (prefers-color-scheme: dark)to set the starting state, but that takes extra rules, and the checkbox then needs a way to override the media query. - The checkbox must be reachable and labeled. A hidden checkbox with a styled label still needs keyboard access, so avoid
display: noneon the input. Visually hide it in a way that keeps it focusable instead.
Specificity across these patterns
Each pattern above produces a rule with more specificity than a plain class rule. The specificity of :has() equals that of its most specific argument, and that value is added to the rest of the compound selector.
/* (id, class, type) specificity */
.a:has(#x) { } /* (1,1,0): the :has() argument's ID counts */
.a:has(.b, p) { } /* (0,2,0): the most specific argument in the list counts */So :root:has(#dark-toggle:checked) has specificity (1,2,0): the ID, plus the :checked class-level pseudo-class, plus the :root pseudo-class. That beats a later body.light override. If your dark theme does not apply, check whether another rule has higher specificity before looking elsewhere. The ID in the toggle selector is a good reason to use a class on the checkbox if you want lower specificity.
Providing a fallback
All three patterns need :has() support. A declaration inside a rule whose selector the browser does not understand is dropped with the whole rule, so the base styles remain. For safe layering, put the enhancement inside @supports selector():
.card {
padding: 1rem;
}
@supports selector(:has(*)) {
.card:has(img) {
display: grid;
}
}Design the base styles to be usable on their own. A card without the grid layout is still readable, and a form without the color hints still works.
Common mistakes
- Writing
.card:has(:not(img))when you meant "no image". - Using the descendant form when cards can nest, so inner content styles the outer card.
- Forgetting the
placeholderattribute when using:placeholder-shown. - Nesting
:has()inside:has(), which is not allowed. Combine conditions in one argument instead. - Putting a pseudo-element inside the argument, such as
:has(::before). Pseudo-elements are not valid there.
Exercise
A form wrapper .field contains an input. Write one rule that makes the wrapper's label turn orange while the input has keyboard focus, and explain why .field:has(input:focus-visible) label is a better choice than label:focus-visible.
Show answer
.field:has(input:focus-visible) label { color: orange; }. A label is not focusable, so label:focus-visible would never match. The :has() rule lets the wrapper test the focus state of the input, which then selects the label inside it.
Exercise
Write a selector for a .card that has no direct img child, and name the difference between it and .card:has(:not(img)).
Show answer
.card:not(:has(> img)). It matches cards whose direct children contain no img. .card:has(:not(img)) matches any card that has at least one descendant that is not an img, so a card with an image and a heading still matches it.
Exercise
Your dark theme rule :root:has(#dark-toggle:checked) { --bg: #121212; } is overridden by html body.page { --bg: white; } placed later in the stylesheet. Which rule wins, and why?
Show answer
The :root:has(#dark-toggle:checked) rule wins. Its specificity is (1,2,0), counting the ID inside :has(), :checked, and :root. The later rule has specificity (0,1,2), so order does not matter and the dark rule applies, assuming both set the same property on the same element. If they set it on different elements, inheritance and each element's own rules decide instead.