7 :has() Recipes That Delete Your JavaScript

October 15, 2026 · 9 min read · CSS

By Syed · Frontend Engineer & Creator of UITweak

For twenty years, CSS had a hard rule: selectors only look down and sideways. You could style a child based on its parent, never the other way around. So every codebase collected the same JavaScript: a function that watches a child and toggles a class on the parent. Card has an image? Add card--with-image. Input is invalid? Add field--error. A nav child is active? Add section--open. The browser already knew all of this state. CSS just could not ask about it. Then the CSS :has() selector arrived, the first true CSS has selector, and the parent selector era began.

:has() ends that. It is the parent selector: it styles an element based on what is inside it. The through-line of every recipe below is the same: find the JavaScript whose only job is reporting child state to a parent, and delete it.

30-second version: .card:has(img) selects any card containing an image. That one pattern replaces the card--with-image class your JavaScript used to toggle. Baseline since December 2023 (Chrome 105+, Safari 15.4+, Firefox 121+), so it is safe to use without a fallback story in most projects.

Recipe 1: Cards that adapt to their content

The classic. Some cards have a thumbnail, some do not, and the layout should differ. The old way: your template or script adds card--with-image whenever an image exists. The new way:

.card {
  display: grid;
  gap: 1rem;
  padding: 1.5rem;
}

/* image present: two-column layout, JS class deleted */
.card:has(img) {
  grid-template-columns: 96px 1fr;
  align-items: center;
}

/* featured treatment only when the image exists */
.card:has(img) {
  box-shadow: 0 20px 40px -12px rgb(0 0 0 / 0.25);
}

Notice the second block: conditional presentation is now declarative too. Any style that used to live behind the toggled class moves straight into the :has() rule.

Recipe 2: Form validation without a single listener

Form scripts love toggling error classes on the field wrapper when an input fails validation. Pair :has() with :user-invalid (covered in our user-valid guide) and the wrapper styles itself:

.field .error {
  display: none;
}

/* the wrapper reacts to the input inside it */
.field:has(input:user-invalid) input {
  border-color: #ef4444;
}

.field:has(input:user-invalid) .error {
  display: block;
}

/* and the success case, free of charge */
.field:has(input:user-valid) input {
  border-color: #22c55e;
}

No submit handler, no blur listener, no class bookkeeping. The browser tracks validity; :has() just asks about it.

Recipe 3: Highlight the nav parent of the active page

In a sidebar with collapsible sections, the section heading should look active when any child link is the current page. Traditionally the router or a script walks up the DOM to add a class. Now:

.nav-section-title {
  color: inherit;
  font-weight: 400;
}

/* any active link inside lights up the section heading */
.nav-section:has(.nav-link.active) > .nav-section-title {
  color: #4f46e5;
  font-weight: 600;
}

/* auto-expand the section too */
.nav-section:has(.nav-link.active) .nav-children {
  display: block;
}

This works with server-rendered active states as well as client routers, because it reacts to the DOM, not to your framework.

Recipe 4: Empty states that show themselves

Lists, tables, and search results all need an "empty" treatment, and scripts usually toggle it. Let the stylesheet notice the emptiness:

.empty-state {
  display: none;
  padding: 3rem;
  text-align: center;
}

/* list has no items: show the empty state */
.panel:has(ul:empty) .empty-state {
  display: block;
}

/* table with no rows: hide the header too */
table:has(tbody:empty) thead {
  display: none;
}

One caution: :empty means truly empty, not even whitespace. If your template leaves a newline inside the ul, it is not empty. Keep the markup tight or strip the whitespace server-side.

Recipe 5: Quantity queries

This is the one listicles never explain properly. :has(> :nth-child(5)) selects a parent with at least five children, because the fifth child exists. That turns "restyle when the list gets long" into pure CSS:

.grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
}

/* 5 or more items: denser layout */
.grid:has(> :nth-child(5)) {
  grid-template-columns: repeat(4, 1fr);
}

/* exactly 3 items: center them */
.grid:has(> :nth-child(3):last-child) {
  grid-template-columns: repeat(3, 1fr);
  justify-content: center;
}

The trick is :nth-child(n):last-child for "exactly n". Combine the two patterns and you can build full responsive-to-count layouts with zero JavaScript and zero resize observers.

Recipe 6: A zero-JavaScript theme toggle

Put :has() on :root and the whole page can react to a checkbox. No script, no localStorage dance for the styling part:

<label class="theme-switch">
  <input type="checkbox" id="theme-toggle" />
  <span>Dark mode</span>
</label>
:root {
  color-scheme: light;
  --bg: #ffffff;
  --text: #0f172a;
}

/* the checkbox is checked: the whole page goes dark */
:root:has(#theme-toggle:checked) {
  color-scheme: dark;
  --bg: #0f172a;
  --text: #e2e8f0;
}

body {
  background: var(--bg);
  color: var(--text);
}

color-scheme is the detail people forget: it flips form controls, scrollbars, and other UA chrome along with your variables. (Persisting the choice across visits still needs a line of JS for storage, but the styling itself is done.)

Recipe 7: Layout that notices its sidebar

Pages that sometimes render an aside and sometimes do not usually get two layout classes from the template. One rule replaces both:

.layout {
  display: grid;
  grid-template-columns: 1fr;
  gap: 2rem;
}

/* sidebar present: make room for it */
.layout:has(aside) {
  grid-template-columns: 240px 1fr;
}

/* and hide the "open filters" button when there is nothing to open */
.layout:has(aside) .filters-toggle {
  display: none;
}

This pattern generalizes: any optional region (banner, TOC, related posts) can reshape the layout around itself without the template knowing.

Gotchas before you delete all the JS

1. Keep the subject specific

:has() is relational, so the browser re-evaluates it when the DOM changes. .card:has(img) on a few dozen cards is cheap. *:has(img) on every element of a large app is not. Scope the selector to the component you mean and you will never feel the cost.

2. You can only style the element carrying :has()

article:has(img) styles the article. There is no way to reach further up from the same rule: the grandparent needs its own :has(). Style flows from the matched element outward, never upward past it.

3. It sees descendants and following siblings, not ancestors or previous siblings

h2:has(+ p) works: the h2 looks at its next sibling. But nothing lets an element react to a previous sibling or an ancestor. If your design needs "style X because Y came before it", reorder the DOM or keep that one line of JS.

4. No pseudo-elements inside :has()

:has(::before) is invalid and the whole selector is dropped. Also remember the arguments must be relative selectors, so a leading combinator like :has(> img) needs the child combinator written exactly that way. Forgiving parsing means one bad selector in the list does not kill the others, but a bad pseudo-element kills its own selector.

The fallback story

:has() reached Baseline in December 2023: Chrome 105+, Safari 15.4+, Firefox 121+. For most audiences that is the whole story, no fallback needed. If you still support older browsers, gate the enhancement and keep the old class as the base:

.card--with-image {
  /* old JS-toggled class: the fallback */
  grid-template-columns: 96px 1fr;
}

@supports selector(:has(img)) {
  .card:has(img) {
    grid-template-columns: 96px 1fr;
  }
  /* the JS class becomes redundant where :has() works */
  .card--with-image {
    grid-template-columns: inherit;
  }
}

The @supports selector(...) syntax is the correct feature test. Do not test :has() inside a custom property, it always passes there.

Generate the card styles, then gate them

Recipe 1 left a detail hanging: the featured treatment for cards with images still needs a good shadow. uitweak's shadow studio builds layered, realistic shadows visually: dial in the depth, copy the CSS, and drop it inside .card:has(img). Cards without images keep the flat default, cards with images get the studio treatment, and no JavaScript decides which is which.

Browser support

  • Chrome / Edge: 105+
  • Safari: 15.4+
  • Firefox: 121+

Baseline since December 2023, so every recipe above works in all current browsers. The @supports selector() pattern above is only for the long tail of older versions.

FAQ

Is :has() slow?

Used normally, no. Browsers optimize the common cases. It gets expensive when the subject is broad (*:has()) or when the DOM mutates constantly under a :has() rule. Keep selectors component-scoped, as in the recipes above, and performance is a non-issue.

Can :has() replace all my conditional classes?

The ones that report DOM state, yes. Classes that carry application state (logged in, plan tier, feature flags) still belong in JS. A good rule: if the class exists only because CSS could not see the child, delete it. If it exists because only your app knows the state, keep it.

Why not just keep the JS classes?

They work, but they are a second source of truth that can drift. Every render path, every framework, every CMS template has to remember to toggle them. :has() derives the state from the DOM itself, so it can never be out of sync.

Share this guide