🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

CSS Pseudo-Classes: State, Structure, and :has()

Web StylesđŸŸĸ Free Lesson

CSS Pseudo-Classes: State, Structure, and :has()

A class selector matches what you wrote in the markup. A pseudo-class matches a condition — the element is hovered, focused, the third child, currently valid, or it contains a descendant that matches something else. That extra dimension is why pseudo-classes can express styles that would otherwise need JavaScript toggling classes on and off. Modern CSS has pushed this further than most developers realize: :focus-visible fixed the focus-ring debate, :has() finally gave you a parent selector after thirty years, and :is() and :where() let you write selector groups with explicit specificity control. This lesson covers the interactive states you ship in every component, the structural selectors that remove wrapper divs from your markup, and the logical pseudo-classes that tie styling to meaning.

Interactive states and the focus-visible compromise

Hover, active, and visited are the original trio. Hover styles a pointer over the element; active covers the moment between press and release, which is why button press effects usually scale down slightly there; visited applies only to links the user has opened, and browsers restrict which properties it may color for privacy reasons. Focus is the accessibility-critical one: any element reachable by keyboard receives focus, and removing its outline without a replacement makes your interface unusable without a mouse. The old solution — outline only for keyboard users — required JavaScript sniffing keystrokes. :focus-visible is the native version of that heuristic: browsers decide based on input type and context whether the focus ring was "intentional," so you can style a subtle ring for keyboard users and suppress it for mouse clicks on the same element:

.button {
  padding: 0.6rem 1.1rem;
  border-radius: 8px;
  border: 1px solid #2563eb;
  background: #2563eb;
  color: #ffffff;
  cursor: pointer;
  transition: background 0.15s ease, transform 0.1s ease;
}

.button:hover {
  background: #1d4ed8;
}

.button:active {
  transform: scale(0.97);
}

.button:focus {
  outline: none;
}

.button:focus-visible {
  outline: 2px solid #2563eb;
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.55;
  cursor: not-allowed;
  transform: none;
}

One caution: :focus styling that removes the outline is only safe when :focus-visible provides a visible replacement. And disabled elements do not receive focus at all — if a control is temporarily unavailable but should stay reachable, use aria-disabled and style it with your own attribute selector instead.

Structural selection with nth-child

Structural pseudo-classes select by position among siblings: :first-child, :last-child, :only-child, and the powerful :nth-child(), which accepts an integer, the keywords odd and even, or an an+b formula like 3n+1 (every third item, offset by one). :nth-of-type() narrows the count to a single element type, so p:nth-of-type(2) is the second paragraph among its siblings regardless of what other elements sit between. The classic use cases are table striping, removing margins from the last list item, and alternating backgrounds — all patterns that previously meant adding utility classes in a loop:

.steps {
  list-style: none;
  counter-reset: step;
}

.steps li {
  counter-increment: step;
  position: relative;
  padding: 0.75rem 0 0.75rem 3rem;
  border-left: 2px solid #e2e8f0;
}

.steps li:first-child { padding-top: 0; }
.steps li:last-child { border-left-color: transparent; }

.steps li::before {
  content: counter(step);
  position: absolute;
  left: -1.1rem;
  top: 0.75rem;
  width: 2rem;
  height: 2rem;
  display: grid;
  place-items: center;
  border-radius: 50%;
  background: #2563eb;
  color: #ffffff;
  font-size: 0.85rem;
  font-weight: 700;
}

.striped tbody tr:nth-child(even) {
  background: #f8fafc;
}

.card-grid > *:nth-child(3n + 1) {
  clear: both;
}

A structural selector matches the real DOM, not the visually apparent order — a hidden element still counts toward nth-child, which surprises people styling filtered lists. :nth-child of a class also matches only elements that satisfy both conditions: .item:nth-child(odd) counts all siblings but matches only odd ones that also have the class.

:is() and :where(): grouping with a specificity dial

Writing the same declaration block for h1, h2, h3 is fine, but once those selectors grow long — .sidebar nav a:hover, .footer nav a:hover, .hero nav a:hover — duplication creeps in. :is() accepts a selector list and matches any of them, adopting the specificity of the most specific argument. :where() does the same with zero specificity, which makes it perfect for low-priority defaults that designers can override without !important:

FunctionMatchesSpecificity of the resultBest used for
selector list (comma)Any listed selectorEach rule keeps its ownSimple alternates with no shared extras
:is(a, b)Any argumentHighest specificity among argumentsGrouped base styles that must still win over defaults
:where(a, b)Any argumentAlways zeroLibrary defaults, resets, easily overridden themes
:not(a, b)Anything not matchingHighest specificity among argumentsExclusions that should still count as weight
:where(.prose) :is(h1, h2, h3) {
  line-height: 1.2;
  font-weight: 700;
  margin-block: 1.4em 0.5em;
}

:where(.button, .link, [role="button"]) {
  cursor: pointer;
  transition: color 0.15s ease, background 0.15s ease;
}

:where(.nav-item):not(:last-child) {
  margin-inline-end: 1rem;
}

The :where() wrapper around .prose contributes nothing to specificity, so a plain .prose h2 rule or an inline design token will beat it without escalation tricks. That property makes :where() the right home for design-system defaults.

:has() — the parent selector, finally

For decades, "style a parent based on its children" required JavaScript or sibling-selector contortions. :has() reverses the arrow: .card:has(img) matches cards that contain an image; .form-row:has(:invalid) matches a row containing an invalid input. It is also a state detector for things that used to need event listeners — a fieldset whose legend is empty, a list with no items, a details element that is open. Because :has() can be expensive to evaluate, browsers cap its scope, so extremely broad selectors like body:has(div) may be rejected; keep the arguments as narrow as you can:

.form-field:has(:invalid) {
  border-color: #dc2626;
}

.form-field:has(:focus-within) {
  border-color: #2563eb;
  box-shadow: 0 0 0 3px #2563eb33;
}

.card:has(img) {
  display: grid;
  grid-template-columns: 12rem 1fr;
  gap: 1rem;
  align-items: center;
}

.card:has(img) img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-start-start-radius: 12px;
  border-end-start-radius: 12px;
}

.cart-summary:not(:has(.cart-item))::before {
  content: "Your cart is empty";
  color: #64748b;
}

Note that :has() can appear anywhere in a compound, not only at the end — :has(> .badge) + .title scopes the check to direct children. The :not(:has(...)) combination shown above is particularly useful for empty-state messages that replace JavaScript template rendering.

Form-state selectors that reduce JavaScript

Beyond :invalid and :valid, the specification provides :user-invalid (valid until the user has interacted and left an invalid value — the pattern you actually want, so errors do not flash before typing), :required, :optional, :placeholder-shown, and :read-only. :placeholder-shown lets you dim floating labels only while the field is empty. :in-range and :out-of-range apply to numeric inputs with min and max. None of these replace server validation, but they eliminate a whole class of front-end state plumbing.

focus-within, target, and direction-aware matching

Three more state selectors earn permanent spots in the toolkit. :focus-within matches an element whose subtree contains focus — the parent of an input group reacts when any field inside it is active, which is how floating-label containers and search wrappers get their highlighted border without listeners. Unlike :has(:focus), it has longer support and is the pragmatic choice for this common case; :has() remains the general tool when the descendant condition is not focus itself. :target matches the element identified by the URL fragment, powering anchor-driven tabs, scroll-to panels, and highlight-on-arrival effects with zero script — the hash in the address bar is the state. And :dir() matches content by writing direction, so right-to-left layouts can flip spacing and icon mirroring declaratively once dir is set on the document:

.field-group:has(:invalid) {
  border-color: #dc2626;
}

.field-group:focus-within {
  border-color: #2563eb;
  box-shadow: 0 0 0 3px #2563eb33;
}

.panel:target {
  outline: 2px solid #2563eb;
  outline-offset: 4px;
}

.icon {
  inline-size: 1.25rem;
}

:dir(rtl) .icon {
  transform: scaleX(-1);
}

Treat :target carefully with back navigation — users returning to a page often land with a stale fragment still applied, so styles driven by it should be subtle rather than modal-blocking.

Common Mistakes

Removing the focus outline and never adding a keyboard-visible replacement

Fix: Pair outline: none on :focus with a clear :focus-visible ring so keyboard users always see where they are

:nth-child striping breaks after filtering or hiding items

Fix: Remember nth-child counts hidden elements too; re-render the list or switch to nth-of-type only when types are uniform

:has() selectors so broad the browser drops them for performance

Fix: Keep :has() arguments narrow and scoped to a component root instead of body or document-level selectors

Using :is() in a reset and then being unable to override it

Fix: Use :where() for defaults that must lose to author styles, reserving :is() for grouped styles that should keep their weight

Best Practices

  • Style :focus-visible rather than trying to detect keyboard users with JavaScript
  • Replace loop-generated utility classes with nth-child and nth-of-type where the pattern is purely presentational
  • House design-system defaults in :where() so component styles cascade naturally
  • Use :user-invalid instead of :invalid for inline form errors to avoid punishing users mid-typing
  • Combine :has() with placeholder copy for empty states that need no script

Interview Questions

Q1: What is the difference between :is() and :where()?

Both accept a selector list and match any of the arguments. :is() takes on the highest specificity of its arguments, so it participates in the cascade like the most specific alternative would. :where() always has zero specificity, which makes it ideal for defaults that author styles should override without !important.

Q2: How does :has() change what you can style?

It lets a rule match an element based on its descendants or relatives, effectively a parent selector. A card can lay out differently when it contains an image, a form row can react to an invalid input inside it, and empty states can be expressed with :not(:has(...)) — all without JavaScript class toggling.

Q3: Why is :focus-visible preferred over :focus for accessibility?

Mouse users clicking a button do not usually need a focus ring, but keyboard and assistive-technology users always do. :focus-visible applies only when the browser judges the focus interaction to warrant a visible indicator, giving accessibility without visual noise for pointer users.

Key Takeaways

  • Pseudo-classes match conditions — state, position, or contained content — instead of class names in markup
  • :focus-visible is the accessible default for focus styling; never remove outlines without replacing it
  • :nth-child and :nth-of-type express striping, first/last adjustments, and an+b patterns without utility classes
  • :is() preserves specificity; :where() zeroes it out — choose per whether the rule is a default or a winner
  • :has() unlocks parent and empty-state styling, and :user-invalid improves form error timing
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement