Sub topic 7
Reacting to state with :has()
This chapter assumes you know basic selectors and combinators, the state pseudo-classes :hover, :checked and :focus-visible, and how specificity is calculated. It also assumes you can write a simple :has() selector with a descendant or a direct child, as covered earlier in this tutorial.
Why state is the best use of :has()
Before :has(), CSS could react to state only on the element that was in that state. A checked checkbox could style itself, or the label next to it if the label came later in the HTML. It could not style the form, the page, or an earlier sibling.
:has() removes that limit. Put a state pseudo-class inside :has() and the match moves up to the ancestor, or back to the earlier sibling. The browser re-evaluates the selector whenever the state changes, so the style follows the user's actions with no JavaScript.
The general pattern is:
.wrapper:has(.inner:state) {
/* styles for the wrapper while .inner is in that state */
}The following sections show how that works with the state pseudo-classes you will use most.
State pseudo-classes that work well inside :has()
| Pseudo-class | What it detects | Typical use with :has() |
|---|---|---|
| `:checked` | A checked checkbox, radio button, or selected option | Highlight a selected card, switch a page theme |
| `:focus-visible` | An element focused in a way that should show a focus ring, usually by keyboard | Outline a whole field group |
| `:focus-within` | Not needed here, since `:has(:focus-visible)` is more precise | Use `:has()` when you need the keyboard-only rule |
| `:invalid` | A field that fails its validation constraints | Color the label or show a message area |
| `:placeholder-shown` | A field that is empty and showing its placeholder | Distinguish "empty" from "filled in" |
| `:disabled` | A disabled form control | Dim the whole row |
| `[open]` | A `details` or `dialog` that is open (an attribute, not a pseudo-class) | Lock page scroll, restyle a section |
:has() accepts any selector that makes sense in a relative selector list, so attribute selectors such as [open] and [aria-expanded="true"] work as well as pseudo-classes.
Example: a form field that reacts to its input
A form field usually has a wrapper that holds a label and an input. You want the wrapper to show a focus ring while the user types, and the label to turn red if the value is wrong. Here is a complete page you can save and open.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Field state with :has()</title>
<style>
.field {
display: grid;
gap: 0.25rem;
padding: 0.75rem;
border: 1px solid #ccc;
border-radius: 6px;
max-width: 20rem;
}
.field:has(input:focus-visible) {
outline: 2px solid royalblue;
}
.field:has(input:invalid:not(:placeholder-shown)) label {
color: crimson;
}
</style>
</head>
<body>
<div class="field">
<label for="email">Email</label>
<input id="email" type="email" placeholder="[email protected]" required>
</div>
</body>
</html>Two rules do the work:
.field:has(input:focus-visible)matches the wrapper whenever the input inside it shows a focus ring. The outline appears around the whole field, not only around the input..field:has(input:invalid:not(:placeholder-shown)) labelmatches the label only when the input is invalid and not empty. The:has()part sits in the middle of the selector. After it, a descendant combinator selects the label inside the matched wrapper.
The second rule has a purpose. A required input is invalid as soon as the page loads, because it is empty. If you used :invalid alone, every required field would be red before the user touched anything. Adding :not(:placeholder-shown) limits the error style to fields that have content.
How the browser decides
The match is live. There is no event to wire up and no class to add or remove. The state lives in the DOM and the selector reads it.
A page-level toggle with :checked
State can drive the whole page. This uses a plain checkbox and the :root element, which is the html element.
<label><input type="checkbox" id="dark-toggle"> Dark mode</label>
<main>Page content</main>:root:has(#dark-toggle:checked) {
color-scheme: dark;
}When the box is checked, :root matches and color-scheme: dark switches the default colors of the page. If your own colors are defined with custom properties, you can set those inside the same rule:
:root {
--bg: #ffffff;
--text: #1a1a1a;
}
:root:has(#dark-toggle:checked) {
color-scheme: dark;
--bg: #121212;
--text: #f0f0f0;
}
body {
background: var(--bg);
color: var(--text);
}Every element that reads --bg and --text updates at once, whichever element contains the checkbox.
This approach has limits. The choice is lost on reload unless you store it elsewhere. A :has() toggle is a good fit for demos and for state that does not need to persist. For a real theme switcher, combine it with prefers-color-scheme, or with JavaScript that saves the choice.
Selected cards from radio buttons
A group of radio buttons can drive the style of each option's container. The pattern is the same: the container holds the input, and :has() reads the input's state.
.option {
border: 2px solid #ccc;
border-radius: 8px;
padding: 1rem;
}
.option:has(input[type="radio"]:checked) {
border-color: royalblue;
background: #eef3ff;
}
.option:has(input:disabled) {
opacity: 0.5;
}<fieldset>
<legend>Plan</legend>
<label class="option">
<input type="radio" name="plan" value="basic" checked> Basic
</label>
<label class="option">
<input type="radio" name="plan" value="pro"> Pro
</label>
<label class="option">
<input type="radio" name="plan" value="legacy" disabled> Legacy
</label>
</fieldset>Selecting "Pro" unchecks "Basic" in the radio group. The browser updates both inputs, and both containers re-match. The styles swap without any script.
Page-level state from an open dialog
Attributes that signal state work the same way as pseudo-classes. When a modal dialog is open, you often want to stop the page behind it from scrolling:
body:has(dialog[open]) {
overflow: hidden;
}dialog[open] matches while the dialog has the open attribute, which the browser sets when you call showModal() or show(). When the dialog closes, the attribute goes away and scrolling returns. No cleanup code is needed, which also removes the bug where a script forgets to restore scrolling after an error.
Reacting to state in a later sibling
State is not always inside the element you want to style. Sometimes it sits in a later sibling. Use a relative combinator at the start of the :has() argument:
li:has(+ li input:checked) {
border-bottom-color: royalblue;
}This selects each li whose next sibling li contains a checked input. Without :has(), CSS could not style an earlier sibling at all.
Negating state
Combine :has() with :not() to style the absence of a state. The two orders mean different things:
.field:not(:has(input:checked))matches fields that contain no checked input..field:has(input:not(:checked))matches fields that contain at least one input that is not checked.
For a field with a single checkbox the two are equivalent. For a group, they diverge. In a group of three checkboxes with one checked, the first selector does not match, because a checked input exists. The second does match, because two unchecked inputs exist. Pick the form that matches the question you are asking: "is nothing selected?" or "is anything unselected?".
Common mistakes
- Using
:hoverand expecting only the direct element..card:has(:hover)matches while the pointer is over the card or anything inside it. That is often what you want, but it is not the same as.card:hoveron an element withpointer-eventstricks. - Using
:focuswhere:focus-visibleis meant.:has(input:focus)also matches after a mouse click on the input. Use:focus-visiblewhen you only want keyboard-style focus rings. - Forgetting that
:invalidmatches on load. Pair it with:placeholder-shown, or with a class your script adds after the first interaction, to avoid errors showing before users have done anything. - Targeting pseudo-elements.
:has()cannot contain a pseudo-element such as::before. State on a pseudo-element is not something CSS can read. - Relying on color alone. Red text for an invalid field is not enough for all users. Pair it with text or an icon that you also reveal through
:has(), for example an error message element that is hidden by default.
Exercises
Exercise
You write .field:has(input:invalid) label { color: crimson; } and every required field is red when the page loads, before anyone has typed. What causes this, and how do you change the selector so the error color appears only after the user has entered something?
Show answer
An empty required input is already invalid, so :invalid matches immediately. Add :not(:placeholder-shown) to the input part, giving .field:has(input:invalid:not(:placeholder-shown)) label, and make sure the input has a placeholder attribute so that :placeholder-shown can match when the field is empty.
Exercise
A group contains three checkboxes and exactly one is checked. Does .group:not(:has(input:checked)) match? Does .group:has(input:not(:checked)) match? Explain each answer.
Show answer
The first does not match, because the group does contain a checked input, so :has(input:checked) is true and :not() negates it. The second does match, because the group contains at least one input that is not checked (in fact two). The two selectors answer different questions: "contains no checked input" versus "contains some unchecked input".
Exercise
Write a rule that stops the page from scrolling while any dialog element in the page is open.
Show answer
body:has(dialog[open]) { overflow: hidden; }. The [open] attribute is present while the dialog is shown and removed when it closes, so the rule turns itself on and off.