CSS :has() Selector
For decades, CSS could select a child based on its parent, but
never the reverse — there was no way to style a parent based on
what it contained. The
:has() pseudo-class finally
solves this. Nicknamed the "parent selector," it lets you write
rules like "style this card differently if it contains an image"
or "highlight this form field if its input is invalid" — entirely
in CSS, with zero JavaScript.
The Problem :has() Solves
CSS selectors have always been able to look "downward" or
"forward" — selecting a child of a parent, or a sibling that comes
after another. There was never a way to select an element based on
what comes inside or after it. Before
:has(), this required
JavaScript:
if it contains a <figcaption>"
/* No CSS selector for this */
figure { /* contains figcaption? */ }
Required JavaScript:
if (figure.querySelector('figcaption'))
figure.classList.add('has-caption')
figure:has(figcaption) {
border: 1px solid #ccc;
}
No JavaScript. No classList
manipulation. No MutationObserver
for dynamic content changes.
:has() Syntax
:has() takes a
relative selector as its argument. The element matches if
anything inside its argument's scope matches. The argument can be
a descendant selector (implicit), a direct child (>), or a sibling combinator (+
or ~):
the element being styled
matches if argument found inside
relative selector — any descendant img
/* ── Descendant (implicit) — matches any depth ── */
.card:has(img) { border: 1px solid #ccc; } /* img anywhere inside .card */
/* ── Direct child only ── */
.card:has(> img) { padding: 0; } /* img must be a direct child */
/* ── Next sibling — element followed by X ── */
h2:has(+ p) { margin-bottom: .5rem; } /* h2 immediately followed by p */
/* ── General sibling — element followed somewhere by X ── */
h2:has(~ .alert) { color: red; } /* h2 with an .alert anywhere after */
/* ── Multiple conditions — comma = OR ── */
.card:has(img, video) { overflow: hidden; } /* has img OR video */
/* ── Chaining :has() — AND logic ── */
.card:has(img):has(.badge) { box-shadow: 0 0 0 2px gold; } /* has BOTH */
/* ── Pseudo-classes inside :has() ── */
.field:has(input:focus) { border-color: blue; } /* input currently focused */
.field:has(input:invalid){ border-color: red; } /* input fails validation */
li:has(input:checked) { background: #eef; } /* checkbox inside li is checked */
/* ── Negation — style element WITHOUT something ── */
.card:not(:has(img)) { background: #f8fafc; } /* card has NO image */
Form Validation Styling — Live Demo
The most popular real-world use of
:has(): style the entire field
wrapper (label included) based on the validity of the input inside
it. Type in the fields below — invalid email/short password turns
the wrapper red, valid input turns it green:
/* ── Style the WHOLE wrapper based on the input's validity state ── */
.field-group {
border: 2px solid #e2e8f0;
transition: border-color .2s;
}
/* Invalid — input has content AND fails validation */
.field-group:has(input:invalid) {
border-color: #ef4444;
background: rgba(239,68,68,.04);
}
.field-group:has(input:invalid) .field-label {
color: #ef4444;
}
/* Valid AND has been typed in (not still showing placeholder) */
.field-group:has(input:valid):has(input:not(:placeholder-shown)) {
border-color: #22c55e;
background: rgba(34,197,94,.04);
}
/* ── The label and hint text change colour too — both are
SIBLINGS of the input, styled via the shared parent ── */
.field-group:has(input:focus) {
border-color: #264de4; /* highlight whole group on focus */
box-shadow: 0 0 0 3px rgba(38,77,228,.15);
}
/* ── Why this matters: previously required JS ──
input.addEventListener('input', () => {
wrapper.classList.toggle('error', !input.validity.valid);
});
:has() does this with zero JavaScript and zero event listeners */
Conditional Card Layouts
A common content management problem: some cards have an image, some don't — and the no-image cards should look different (centred text, more padding) instead of leaving an empty gap:
centred + extra padding
/* ── Card without image — auto-detect and adjust layout ── */
.card:not(:has(.card-image)) {
background: #f8fafc;
}
.card:not(:has(.card-image)) .card-body {
padding: 2rem 1rem;
text-align: center;
}
/* ── List item with checkbox checked ── */
.todo-item:has(input:checked) {
opacity: .5;
text-decoration: line-through;
}
/* ── Empty state detection ── */
.results:not(:has(.result-item)) {
display: flex; align-items: center; justify-content: center;
}
.empty-message { display: none; }
.results:not(:has(.result-item)) .empty-message { display: block; }
/* ── Grid that adapts column count based on item count ── */
.grid:has(> :nth-child(4)) { grid-template-columns: repeat(2, 1fr); } /* 4+ items */
.grid:has(> :nth-child(7)) { grid-template-columns: repeat(3, 1fr); } /* 7+ items */
Sibling Selection & Navigation Patterns
:has() with combinators inside
the parentheses unlocks sibling-aware styling — selecting an
element based on what comes after it, which the standalone
~ and
+ combinators alone cannot do
(they only select what comes after the reference, never
the reference itself):
/* ── Highlight a heading if followed by an error message ── */
h2:has(+ .error-message) {
color: #ef4444;
}
/* ── Style items BEFORE a hovered item (impossible without :has) ── */
.menu-item:has(~ .menu-item:hover) {
opacity: .6; /* dim items before the hovered one */
}
/* ── Radio/checkbox group — highlight the selected row ── */
.qty-row:has(input:checked) {
border-color: #264de4;
background: rgba(38,77,228,.05);
}
/* ── Active navigation item (CMS-driven, no JS class toggling) ── */
.nav-item:has(.active-indicator) {
background: rgba(38,77,228,.06);
font-weight: 700;
}
/* ── Table row with a flagged cell ── */
tr:has(.flag-icon) { background: rgba(249,115,22,.08); }
/* ── Parent container reacts to ANY child being hovered/focused ── */
.gallery:has(img:hover) { background: #000; } /* dim background when any thumb is hovered */
.gallery img:hover { transform: scale(1.05); }
:has() Reference
| Pattern | Selects | Use case |
|---|---|---|
| :has(x) | Element containing x at any depth | Card with an image, container with an error |
| :has(> x) | Element with x as a direct child | Strict structural matching |
| :has(+ x) | Element immediately followed by x | Heading followed by a specific element |
| :has(~ x) | Element followed anywhere later by x | Dim items before a hovered sibling |
| :has(x, y) | Element containing x OR y | Card with image OR video |
| :has(x):has(y) | Element containing x AND y | Card with both image AND badge |
| :not(:has(x)) | Element NOT containing x | Empty state, no-image fallback layout |
Try It Yourself
A live form, card and to-do list all powered by
:has() — interact with the
inputs and checkboxes to see the styling react:
Quick Check — Chapter 52
.parent .child) selects something inside a known parent, and sibling
combinators (.a + .b)
select something that comes after a known reference. There was
never a selector that worked in reverse — selecting the parent
based on what's inside it, or selecting an earlier element
based on what comes after it.:has() fills this gap.
.card:has(img) reads as
"select .card if it
contains an img anywhere
inside" — the selector targets the parent (.card) but
the condition is about a descendant (img). This
earned it the nickname "parent selector," even though it's
technically more general — it also works with siblings.Before :has(), this required JavaScript to detect the condition and toggle a class.
:has(img) — implicit
descendant selector. Matches if an
img exists
anywhere inside the element, at any nesting
depth.:has(> img) — direct
child selector. Matches only if an
img is a
direct child of the element — not nested
inside another wrapper.Example:
<div class="card"><div
class="wrap"><img></div></div>—
.card:has(img) matches
(img exists somewhere inside)—
.card:has(> img) does
NOT match (img is a grandchild, not a direct child — the
direct child is .wrap)Use the descendant form (no combinator) for most cases since it's more forgiving of markup structure. Use the child combinator when you need strict structural guarantees.
:not(:has(x)) selects
elements that do NOT contain x — the inverse condition. This
is extremely useful for fallback/empty-state styling:.card:not(:has(.card-image))
— selects cards with no image, letting you give them a
different background, centred text, or extra padding instead
of leaving an awkward gap where the image would have been..results:not(:has(.result-item))
— selects a results container with no result items inside,
letting you show an "empty state" message and centre it,
without any JavaScript checking the DOM.This pattern — detect absence and adjust layout — was previously one of the most common reasons to reach for JavaScript in otherwise static markup. :has() + :not() handles it natively.
<label>, the input
is a descendant of the label. The pseudo-class
:checked only targets the
input itself, not its ancestor label — so without :has(),
there was no way to style the whole label/row when its input
becomes checked..todo-item:has(input:checked) { opacity: .5; }This selects the entire
.todo-item wrapper — and
everything inside it, including text spans and icons —
whenever the checkbox inside it is checked. This is how the
to-do list demo strikes through completed items: the text span
doesn't need its own selector logic; it simply inherits the
dimmed/struck styling from its parent matching
:has(input:checked).This same technique powers radio button "selected card" patterns, toggle switches with full-row highlighting, and accordion headers that change style when their content checkbox is checked.
+
and ~) can only select an
element that comes after a reference point; they can
never select the reference point itself based on what follows
it.h2:has(+ p) selects an
h2 only if it is
immediately followed by a
p — the h2 is being
selected based on a sibling that comes
after it..menu-item:has(~ .menu-item:hover)
— selects menu items that have another hovered menu-item
appearing later in the sibling list. This effectively lets you
dim or style items "before" a hovered item — something
completely impossible with traditional CSS combinators, which
can only style what comes after a state change, never before
it.This pattern is used for "previous items in a list" hover effects, form fields that react to a later error message, and table rows that respond to a flag set on a later cell.
.card:has(img) select?
.label:has(input:checked)
let you style?
:has(img) and
:has(> img)?
- :has(selector): matches an element if anything matching the relative selector exists inside (or, with combinators, near) it. Nicknamed the "parent selector."
-
Descendant form:
.card:has(img)— matches img at any depth inside .card. -
Direct child:
.card:has(> img)— only matches if img is an immediate child. -
Sibling combinators:
h2:has(+ p)(immediately followed by),h2:has(~ .alert)(followed anywhere later by). Enables styling based on what comes AFTER — impossible with standalone combinators. -
Multiple conditions: comma inside = OR (
:has(img, video)). Chaining :has():has() = AND (:has(img):has(.badge)). -
Pseudo-classes inside:
:has(input:checked),:has(input:invalid),:has(input:focus)— react to dynamic states of descendants. -
Negation:
:not(:has(x))selects elements WITHOUT x — ideal for empty states and fallback layouts. -
Form validation: style the entire field wrapper
(label + input + hint) based on
input:valid/input:invalid— zero JavaScript. -
Checkbox/radio rows:
.row:has(input:checked)styles the whole row including text, not just the input.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.