Modern CSS Workshop
Live session · 90 min
How :has() selects parents, previous siblings and component state in pure CSS
For most of CSS's history, the honest answer to "is there a CSS parent selector?" was no. Selectors only flowed downward: you could style a child based on its parent, never a parent based on its child. Developers filled the gap with JavaScript that toggled classes like .has-image or .is-invalid.
:has() is a CSS pseudo-class that matches an element when at least one of the selectors you pass to it matches, measured from that element. .card:has(img) selects every .card that contains an <img>. The styles land on the card, not the image. It is defined in the W3C Selectors Level 4 specification as the relational pseudo-class, and it has worked in every major browser since December 2023.
Calling it a "parent selector" undersells it. Because the argument can use sibling combinators, :has() can also select a previous sibling, react to how many children an element has, and respond to state anywhere inside a component: a checked box, an invalid field, an open dialog.
This guide goes past the usual .card:has(img) demo. You will learn how the browser reads a :has() selector, ten patterns that replace real JavaScript, and the details most tutorials leave out: specificity, the unforgiving argument list, the nesting ban, performance rules you can verify in DevTools, and the accessibility limits of styling-only state.
If selectors and pseudo-classes are new to you, start with the CSS selectors tutorial and the pseudo-classes lesson. This article assumes you are comfortable with both.
Every :has() selector has two parts. The anchor is the element being styled, written before :has. The relative selector inside the parentheses describes what must exist, measured from the anchor. Read A:has(B) as "A, if it has B".
/* Anchor: .card. Relative selector: img (any descendant). */
.card:has(img) {
grid-template-columns: 160px 1fr;
}The relative selector can begin with any combinator. If you leave it out, the browser assumes a descendant. The combinator decides where the browser looks:
figure:has(figcaption) /* any descendant figcaption */
figure:has(> figcaption) /* a direct child figcaption */
h2:has(+ p) /* an h2 immediately followed by a p */
h2:has(~ .warning) /* an h2 with a .warning sibling anywhere after it */The last two are the important ones. Sibling combinators only look forward, so h2 + p styles the paragraph. Wrapping the sibling inside :has() flips the subject: h2:has(+ p) styles the heading. That is how CSS selects a previous sibling.
A comma-separated list inside :has() means OR. Chaining two :has() calls means AND:
/* OR: an article with a video or an iframe */
article:has(video, iframe) { aspect-ratio: auto; }
/* AND: a form with a required field and a submit button */
form:has([required]):has(button[type="submit"]) { padding-block-end: 2rem; }This is the most common logic bug with :has(), and almost no tutorial calls it out. The two forms ask different questions:
.card:not(:has(img)) means the card contains no image at all..card:has(:not(img)) means the card contains at least one element that is not an image, which is true for nearly every card./* Correct: cards without any image get a text-only layout */
.card:not(:has(img)) {
grid-template-columns: 1fr;
}
/* Gallery figures that contain nothing but images */
figure:not(:has(> :not(img))) {
display: grid;
grid-template-columns: repeat(2, 1fr);
}The second rule uses a double negative. "Not having a direct child that is not an image" means every direct child is an image.
The demos below run on real :has() rules, not JavaScript class toggles. React only adds or removes elements. Every visual change comes from CSS reacting to the DOM. Check the box, add items, or type an invalid email and compare the result with the rule shown beside each demo.
Toggle the image or check the box. The card's layout and border are set entirely by :has().
Modern CSS Workshop
Live session · 90 min
.card:has(> .media) {
grid-template-columns: 96px 1fr;
}
.card:has(input:checked) {
border-color: #8b5cf6;
}Items: 3. The grid wraps at four items and shows an empty state at zero.
.grid:has(> :nth-child(4)) {
grid-auto-flow: row; /* 4+ items */
}
.grid:has(> :only-child) {
justify-content: center;
}
.grid:not(:has(> *))::after {
content: "Empty: no items";
}Type an invalid email and leave the field. :user-invalid waits for interaction, so nothing turns red on page load.
Enter a valid email address.
.field:has(input:required) label::after {
content: " *";
}
.field:has(input:user-invalid) label {
color: #dc2626;
}
.field:has(input:user-invalid) .error {
display: block;
}These patterns let a component's layout follow what is actually inside it. That removes a whole class of modifier classes such as .card--no-image or .grid--three, which CMS editors forget to set.
.card {
display: grid;
gap: 1rem;
}
.card:has(> img, > picture) {
grid-template-columns: minmax(120px, 30%) 1fr;
}
.card:has(> img, > picture) h3 {
font-size: 1.125rem;
}The child combinator (>) is intentional. It stops an image nested deep in the card's body text from triggering the media layout, and it is cheaper for the browser to check. More on that in the performance section.
Before :has(), quantity queries relied on hard-to-read :nth-last-child tricks applied to every child. Now the container can ask how many children it has. :has(> :nth-child(4)) is true when a fourth child exists, which means at least four children:
/* 1–3 items: one row */
.gallery { display: grid; grid-auto-flow: column; }
/* 4+ items: switch to a wrapping grid */
.gallery:has(> :nth-child(4)) {
grid-auto-flow: row;
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
}
/* exactly 1 item: center it */
.gallery:has(> :only-child) { justify-content: center; }
/* exactly 3 items */
.gallery:has(> :nth-child(3):last-child) { --cols: 3; }
/* at most 3 items */
.gallery:not(:has(> :nth-child(4))) { gap: 2rem; }Watch for one mistake that appears in several popular guides: .list:has(> * :nth-child(4)) has a space after *, so it checks for a fourth grandchild. Keep :nth-child attached directly to the > combinator.
Pair this with CSS Grid and you get layouts that rebalance themselves as editors add or remove items.
:empty only matches an element with no children at all, and a single whitespace character or line break counts as content. Most templating engines leave that whitespace behind. Checking for the element you care about is more reliable:
.results:not(:has(> li)) {
min-height: 12rem;
background: url("/empty-state.svg") center / 8rem no-repeat;
}
.results:not(:has(> li))::after {
content: "No results match your filters.";
}.menu li:has(> ul) > a::after {
content: "";
border: 0.3em solid transparent;
border-top-color: currentColor;
margin-inline-start: 0.4em;
display: inline-block;
translate: 0 0.15em;
}The arrow only appears on items that really have a nested list, so it never goes stale when someone edits the menu.
:has() gets most interesting when the relative selector includes a state pseudo-class such as :checked, :focus-visible, :user-invalid or :modal. The parent can now react to user interaction inside it.
Styling the label and the wrapper of an invalid field used to need JavaScript. Use :user-invalid rather than :invalid. :invalid matches the moment the page loads, so required fields show errors before the user has typed anything. :user-invalid waits until the user has interacted with the field. It has been Baseline since 2023.
.field:has(input:user-invalid) {
--field-color: #dc2626;
}
.field:has(input:user-invalid) label { color: var(--field-color); }
.field:has(input:user-invalid) .error-message { display: block; }
/* Mark required fields once, from the input itself */
.field:has(input:required) label::after {
content: " *";
color: #dc2626;
}
/* Highlight the whole group for keyboard users */
.field:has(input:focus-visible) {
outline: 2px solid var(--focus-ring, #7c3aed);
outline-offset: 4px;
}:focus-within also styles a parent on focus, but it matches mouse clicks too. :has(:focus-visible) follows the browser's keyboard-focus heuristic, which is usually what you want for focus rings. The form validation tutorial covers the HTML attributes these selectors depend on.
A common hover effect scales the hovered item and slightly scales its neighbours. The next neighbour has always been easy to reach. :has() adds the previous one:
.dock-item:hover { scale: 1.4; }
.dock-item:hover + .dock-item,
.dock-item:has(+ .dock-item:hover) { scale: 1.15; }
/* Every item before the hovered one, e.g. a rating bar */
.rating-step:has(~ .rating-step:hover) { background: #fbbf24; }Add :focus-visible alongside :hover in real projects so keyboard users get the same feedback. The CSS transitions lesson shows how to animate the scale change smoothly.
tr:has(input[type="checkbox"]:checked) {
background: color-mix(in oklch, #7c3aed 12%, transparent);
}
/* Show a bulk-action bar only when something is selected */
.bulk-actions { display: none; }
.table-wrapper:has(tbody input:checked) .bulk-actions { display: flex; }The bulk-action bar needs no state management. The DOM already knows whether a box is checked.
Pages scrolling behind an open modal is a long-standing annoyance. With the native <dialog> element opened with showModal(), one rule fixes it:
html:has(dialog:modal) {
overflow: hidden;
scrollbar-gutter: stable; /* avoid layout shift when the scrollbar disappears */
}This anchors on the root element, which the performance section tells you to avoid. It is still a reasonable exception. The inner selector is narrow (a dialog in the modal state), it changes rarely, and the alternative is JavaScript that adds and removes a class on <body>. Make these exceptions deliberately, not by habit.
:root { color-scheme: light dark; }
:root:has(#theme-dark:checked) { color-scheme: dark; }
:root:has(#theme-light:checked) { color-scheme: light; }
body {
background: light-dark(#ffffff, #0b1020);
color: light-dark(#1f2937, #e5e7eb);
}light-dark() resolves against color-scheme, so one toggle updates every color token. This version does not remember the choice between visits. If you need persistence, use a few lines of JavaScript to save it and set an attribute, and keep :has() for state that only lasts for the session. For organizing the tokens, see CSS custom properties.
.layout { display: grid; grid-template-columns: 1fr; }
.layout:has(> .sidebar) { grid-template-columns: 1fr 18rem; }
.layout:has(> .sidebar.is-collapsed) { grid-template-columns: 1fr 4rem; }One layout component now serves pages with and without a sidebar, with no extra wrapper classes passed down from the template.
These details explain most "why doesn't my :has() selector work?" questions.
According to MDN, :has() takes the specificity of the most specific selector in its argument, just like :is() and :not(). The pseudo-class itself adds nothing beyond that.
.card:has(img) /* (0,1,1): class + type */
.card:has(img, #promo) /* (1,1,0): the ID wins, even when only img matches */
.card:has(.badge.new) /* (0,3,0) */The second line catches people out. Adding an ID to the list raises the specificity of the whole selector even on cards where only the image matched. If you need low-specificity defaults, wrap the selector in :where(). Our !important and specificity lesson explains how these weights compare.
Early drafts made :has() forgiving: an invalid selector in the list was ignored and the rest still worked. That broke jQuery, which has its own non-standard selectors such as :contains(). In December 2022 the CSS Working Group resolved to make :has() unforgiving, and only :is() and :where() stayed forgiving.
So today, one invalid or unsupported selector inside :has() invalidates the entire rule:
/* Whole rule dropped if the browser doesn't know :future-state */
.panel:has(.open, :future-state) { border-color: gold; }
/* Safer: wrap the risky part in :is(), which is forgiving */
.panel:has(.open, :is(:future-state)) { border-color: gold; }Older articles that describe :has() as forgiving are out of date.
The specification forbids :has() inside another :has(). A selector like .a:has(.b:has(.c)) is invalid and the whole rule is dropped. Flatten the relationship with combinators instead: .a:has(.b .c).
You cannot write .card:has(::before) or .input-wrap:has(::placeholder). MDN explains why: many pseudo-elements only exist because of their ancestors' styles, so letting :has() query them could create cycles. If you need to know whether a placeholder is showing, use the :placeholder-shown pseudo-class, which is allowed: .field:has(input:placeholder-shown).
:has() is fast enough for production. Browser engineers spent years on invalidation strategies before shipping it. But it is the first selector where a change deep inside an element can change the style of its ancestor, so a careless selector can make style recalculation expensive on large, frequently changing pages.
A :has() rule costs two things. The browser has to decide when to re-check it, and it may have to walk part of the tree to answer it. Each rule below reduces one of those costs.
/* Avoid: every DOM change in the page is a candidate for re-checking */
body:has(.product-card .badge) .header { }
/* Prefer: the check stays inside the component */
.product-card:has(.badge) { }MDN's performance guidance specifically names body, :root and * as poor anchors. The modal scroll lock above is a reasonable, deliberate exception. Page-wide state switches are not.
.list:has(> li) only looks at direct children. .list:has(li) searches every descendant. Wherever the markup allows, use the child or adjacent-sibling combinator.
:has(*), :has(div) and :has(.foo > *) match on almost any DOM mutation inside the anchor. Prefer arguments that combine a class or attribute with a state, such as :has(> input:checked). Those change rarely and match few elements.
Chrome DevTools can show the real cost. In the Performance panel, open capture settings, turn on Enable CSS selector stats, record an interaction, then select a Recalculate Style event and open the Selector stats tab. It lists elapsed time, match attempts and match count for every selector, as described in Google's selector stats guide. If a :has() rule appears near the top, narrow its anchor or its argument. For broader techniques, see the CSS performance tutorial.
:has() is Baseline widely available. It has worked in all major engines since Firefox shipped it in December 2023:
Check Can I use for current global usage. Any article that still tells you to enable a Chrome flag or wait for Firefox is several years out of date.
If you support older browsers, put enhancements behind @supports selector() and make sure the default styles stand on their own:
/* Baseline: always stacked */
.card { display: grid; gap: 1rem; }
@supports selector(:has(a)) {
.card:has(> img) { grid-template-columns: 30% 1fr; }
}
/* Fallback only for browsers without :has() */
@supports not selector(:has(a)) {
.card.has-image { grid-template-columns: 30% 1fr; }
}selector() checks whether the browser can parse the selector, which is what matters given the unforgiving argument list. See the @supports reference on MDN for the full syntax.
Every DOM API that accepts a selector also accepts :has(), which is handy for tests and for scripts that need to agree with your CSS:
// Feature detection
const hasSupport = CSS.supports("selector(:has(a))");
// All cards that contain an image
document.querySelectorAll(".card:has(> img)");
// Does this form currently contain an invalid field?
form.matches(":has(:user-invalid)");
// Nearest ancestor section that has a heading
button.closest("section:has(h2)");The DOM manipulation tutorial covers these methods in depth.
:has() and container queries are both described as "component-level responsive design", but they answer different questions:
The two CSS features combine well. A card can use :has(> img) to choose a media layout and an @container query to decide whether that layout is horizontal or stacked:
.card-wrapper { container-type: inline-size; }
.card:has(> img) { display: grid; gap: 1rem; }
@container (min-width: 32rem) {
.card:has(> img) { grid-template-columns: 40% 1fr; }
}:has() changes how things look. It does not change what assistive technology announces. That gap is where most accessibility bugs in :has()-heavy code come from.
.field:has(input:user-invalid) does not tell a screen reader anything. Keep native validation messages, or connect your error text with aria-describedby, and set aria-invalid when you show custom errors.:has(:hover) pattern should have a matching :has(:focus-visible) version.<input> that can receive focus. A checkbox hidden with display: none cannot receive focus at all. If the control describes an expandable region, a <button aria-expanded> or a <details> element usually communicates it better.:has() applies display: none or visibility: hidden, that content also leaves the accessibility tree. That is correct for a closed menu and a bug for an error message.The CSS accessibility tutorial goes deeper into focus styles and accessible hiding techniques.
:has() is one of the few CSS features that removes JavaScript from real codebases instead of adding an alternative to it. To use it well:
A:has(B) as "A, if it has B". The anchor gets the styles.+ and ~ inside :has() to select previous siblings, and :has(> :nth-child(n)) for quantity queries.:not(:has(x)) means "no x". :has(:not(x)) means "something that isn't x".:has() or put pseudo-elements inside it.> or +, and verify the cost with DevTools selector stats.:has(), but communicate state with HTML and ARIA.Your next step: find one modifier class in your codebase that a template sets because of content (.has-image, .is-empty, .with-sidebar), replace it with a :has() selector, and delete the code that set it.
Yes, and more. .parent:has(.child) styles the parent when it contains a matching child, which is what people mean by a parent selector. Because the argument can start with + or ~, :has() can also select previous siblings, and with :nth-child() it can count children.
Yes. :has() is Baseline widely available. It shipped in Safari 15.4 (March 2022), Chrome and Edge 105 (August 2022), and Firefox 121 (December 2023). Use @supports selector(:has(a)) only if you still need to support browsers older than those.
The most common causes are an invalid or unsupported selector inside the argument (the argument list is unforgiving, so one bad item drops the whole rule), nesting :has() inside another :has(), putting a pseudo-element such as ::before inside it, or using a descendant argument when you meant a direct child with >.
.card:not(:has(img)) matches cards that contain no image at all. .card:has(:not(img)) matches cards that contain at least one element that is not an image, which is almost every card. You usually want the first form.
Not when written carefully. Anchor it on a specific component instead of body, :root or , constrain the argument with `>` or `+`, and avoid wildcard arguments like `:has()`. Use the Selector stats tab in Chrome DevTools' Performance panel to measure real costs.
It takes the specificity of the most specific selector in its argument, like :is() and :not(). .card:has(img) is (0,1,1), and .card:has(img, #promo) is (1,1,0) even when only the image matches.
Yes. querySelector(), querySelectorAll(), matches() and closest() all accept :has() in browsers that support it, for example form.matches(':has(:user-invalid)'). Detect support with CSS.supports('selector(:has(a))').
No. The specification forbids nesting :has(), and browsers drop the whole rule. Rewrite .a:has(.b:has(.c)) as .a:has(.b .c) using combinators.
Continue your learning journey with these related topics