← Back to CSS
55

`:has()` in depth: visual logic without JavaScript

Master `:has()` so you can style parents and relationships between elements, with practical patterns for forms, cards and interface states.

📘 Theory

The right mental model

Think of `:has()` as a boolean condition applied to the current element.

In `.card:has(img)`, you are not selecting the image. You are selecting the card if it contains an image. That changes the way CSS can reason about structure, because now the container can react to what happens inside it.

In forms, `:has()` enables broader state rules such as `form:has(:invalid)` or `.field:has(input:focus)`. The result is less JavaScript and fewer temporary state classes.

  • Select parents based on content or internal state.
  • Build visual feedback without depending on JavaScript events.
  • Reduce helper classes and keep HTML cleaner.

Real patterns with `:has()`

Three recurring patterns you will actually use in product work.

1

Pattern 1: enriched cards. If a card contains media, increase its visual priority or change its layout.

2

Pattern 2: active field wrappers. The field container reacts to the focused input and makes interaction more obvious.

3

Pattern 3: invalid forms. The submit button reflects the global form state and discourages premature submission.

Good practices

1

Avoid unreadable chains such as `:has(:not(...):is(...))` when they do not add real value. Prefer rules that remain obvious at the component level.

2

Limit the scope of the selector: `.checkout-form:has(:invalid)` is usually better than a broad global rule on every `form`.

3

When the condition is business-critical, document the intent with a short comment so the rule stays understandable over time.

🧪 Learn by doing

Example Interactive demo: contextual form The field wrapper changes when there is focus or an invalid state.

🏁 Challenges

Challenge Challenge: conditional card styling Highlight `.card` only if it contains an image.

🧰 Resources

Useful links

Test

Check your knowledge with a test about CSS.

Test for CSS

What is this?

I'm Cristian Eslava and I sometimes build websites so both you and I can learn and experiment. culTest

I made this in February 2026 to make learning easier for my students. The idea is to learn web development by practicing and to keep expanding the project with new topics, tests and challenges.

It draws inspiration from MDN, W3Schools, CodePen, Manz and many other web development references. I wanted to combine useful theory, runnable examples, challenges and the testing system I had already built for culTest. culTest

If you liked it, if you didn't, or if you want to get in touch, write to me at cristianeslava@gmail.com