CSS Selectors Beyond the Basics: Combinators, Attribute Selectors, and Pseudo-Classes

Advanced CSS selectors explained: the four combinators, attribute operators, structural and form pseudo-classes, and :is(), :where() and :not().

Executive Summary: Most class names in a typical stylesheet exist to describe something the HTML already says: this link is the current page, this field is invalid, this item is the last one, this panel is open. Combinators, attribute selectors and pseudo-classes let CSS read that information directly. The result is less markup, fewer JavaScript-managed classes, and styles that cannot drift out of sync with accessibility state.
Four CSS selector examples including a child combinator, attribute selector and nth-child pseudo-class

Open almost any component library and you will find markup like <a class="nav-link nav-link--active is-current" aria-current="page">. The aria-current attribute already tells assistive technology which link is active. The two extra classes tell CSS the same thing, and someone has to keep all three in sync. When they drift, sighted users and screen reader users see different truths.

Advanced CSS selectors are the selector types beyond plain type, class and ID: combinators, which match elements by their relationship to other elements; attribute selectors, which match on any attribute and its value; and pseudo-classes, which match on state, position in the tree or user interaction. All of them are defined in Selectors Level 4, and everything in this guide works in every current browser.

My position: if your HTML already encodes a state, style that state, not a class that mirrors it. Classes are for naming components. Selectors are for reading facts.

How browsers match selectors

Browsers read a complex selector from right to left. For .sidebar ul li a, the engine first finds every a, then checks whether each has an li ancestor, then a ul, then .sidebar. The rightmost part is called the subject or key selector, and it is the element that actually gets styled.

Two consequences follow. First, the subject is what matters for reading a rule: ask “which element gets these styles?” and look at the right end. Second, performance worries about long selectors are mostly outdated. Engines cache and filter so aggressively that selector cost almost never shows up in a profile. Write selectors for clarity and low specificity, not micro-speed. The cases that do cost something, such as broad :has() rules on huge DOMs, are covered in the performance-safe CSS guide.

The four combinators

A combinator sits between two compound selectors and describes how the elements relate.

Combinator Syntax Matches B when Example
Descendant A B B is anywhere inside A .prose a
Child A > B B is a direct child of A .menu > li
Next sibling A + B B immediately follows A, same parent h2 + p
Subsequent sibling A ~ B B follows A anywhere later, same parent .error ~ .hint

The descendant combinator is the default and the riskiest. .card a also matches links inside a nested card, a footer inside the card, and any third-party widget dropped inside it. Prefer the child combinator when you mean “my own items”. It keeps components from styling each other by accident.

The stack pattern with the sibling combinator

The next-sibling combinator gives you one of the most useful layout rules in CSS: space between items, never before the first one.

.stack > * + * {
  margin-block-start: var(--stack-space, 1rem);
}

Read it right to left: any child that has a previous sibling gets top margin. The first child has no previous sibling, so it gets none. In flex and grid containers, gap does the same job. For flowing article content, where headings, paragraphs and figures sit in normal block flow, the stack pattern still wins, because you can vary the space per element type:

.prose > * + * { margin-block-start: 1em; }
.prose > * + :is(h2, h3) { margin-block-start: 2em; }  /* more room above headings */
.prose > :is(h2, h3) + * { margin-block-start: 0.5em; }  /* tighter below them */

Attribute selectors

Attribute selectors match on any HTML attribute, including data-* and ARIA attributes. They have the same specificity as a class, (0, 1, 0), so they cost nothing extra.

Selector Matches when the attribute Practical example
[attr] exists, with any value [disabled], [hidden]
[attr="v"] equals v exactly [aria-expanded="true"]
[attr~="v"] contains v as a space-separated word [rel~="noopener"]
[attr|="v"] equals v or starts with v- [lang|="en"] matches en and en-IN
[attr^="v"] starts with v a[href^="mailto:"]
[attr$="v"] ends with v a[href$=".pdf" i]
[attr*="v"] contains v anywhere a[href*="utm_"]

Add i before the closing bracket to match case-insensitively. a[href$=".pdf" i] catches both report.pdf and REPORT.PDF. Attribute values in HTML are case-sensitive for selector purposes unless the attribute is one HTML defines as case-insensitive, such as type, so the flag removes a whole class of bugs.

Style state through ARIA attributes

The best use of attribute selectors is styling interactive state through the same attributes that assistive technology reads:

/* The visual state can never disagree with the accessible state */
.nav a[aria-current="page"] {
  font-weight: 600;
  text-decoration: underline;
}

.accordion__trigger[aria-expanded="true"] .accordion__icon {
  rotate: 180deg;
}

.tab[aria-selected="true"] {
  border-block-end: 2px solid currentColor;
}

Now the JavaScript has exactly one job: toggle aria-expanded. If it forgets, the bug is visible to everyone, which means it gets reported and fixed. With a separate .is-open class, a missing ARIA update stays invisible to the developers who test only with a mouse.

Pseudo-classes, grouped by what they read

Pseudo-classes start with a single colon and match states that are not written as plain attributes, or not written in the markup at all. They group naturally by what they observe.

User interaction

  • :hover and :active: pointer over the element, and the element being pressed.
  • :focus: the element has focus by any means.
  • :focus-visible: the element has focus and the browser judges a visible indicator useful, typically keyboard focus. Use it for focus rings so mouse users do not see rings on click while keyboard users always do.
  • :focus-within: the element or any descendant has focus. Useful for highlighting a whole form row or keeping a dropdown open while focus is inside it.
:where(a, button, input, select, textarea):focus-visible {
  outline: 2px solid var(--focus-ring, Highlight);
  outline-offset: 2px;
}

Form state

Forms carry a lot of state, and CSS can read nearly all of it: :checked, :disabled, :enabled, :required, :optional, :read-only, :placeholder-shown, :indeterminate, :in-range and :out-of-range, :autofill, and validity through :valid and :invalid.

The validity pair has a usability problem: :invalid matches the moment the page loads, so every empty required field turns red before the user has typed anything. :user-invalid and :user-valid fix this. They only match after the user has interacted with the field, and they have worked in all major browsers since 2023.

input:user-invalid {
  border-color: var(--danger);
}

input:user-invalid + .field-error {
  display: block;   /* show the message only after the user has tried */
}

Element state

Newer pseudo-classes read the state of built-in interactive elements:

  • :open matches an open <details>, <dialog> or <select> picker. It is the newest pseudo-class in this list, so check browser support before relying on it. It replaces details[open] style attribute checks.
  • :popover-open matches an element with the popover attribute while it is shown.
  • :modal matches a dialog opened with showModal().
  • :defined matches custom elements once they have been registered, which lets you hide unupgraded web components without a flash.

Location

:any-link matches every a or area with an href, visited or not. :target matches the element whose ID is in the URL fragment, which is useful for highlighting the section a reader jumped to. :visited exists, but browsers only let it change color-related properties, so sites cannot detect your history by measuring layout.

Tree structure

Structural pseudo-classes match by position among siblings: :first-child, :last-child, :only-child, :first-of-type, :last-of-type, :empty and :root. The most powerful is :nth-child(An+B), where n counts up from 0 and the selector matches every position the formula produces.

Formula Matches positions Use
:nth-child(odd) or 2n+1 1, 3, 5, … Zebra rows
:nth-child(3n) 3, 6, 9, … Every third card
:nth-child(n+4) 4, 5, 6, … Everything from the fourth on
:nth-child(-n+3) 1, 2, 3 The first three only
:nth-last-child(1) The last item Same as :last-child
:nth-child(2 of .featured) The second element that has .featured Counting within a filtered set

The of S syntax deserves attention. Plain :nth-child(2) counts all siblings, so .featured:nth-child(2) means “the second child, if it happens to be featured”. :nth-child(2 of .featured) means “the second featured child”, which is what people almost always meant. It has been supported in every major browser since 2023.

Quantity queries

Combining structural pseudo-classes lets a list style itself based on how many items it has:

/* When the list has 5 or more items, switch to two columns */
.tags:has(> li:nth-child(5)) {
  columns: 2;
}

/* Style every item in a list of exactly 3 */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
  flex-basis: 33.333%;
}

The second pattern was the old trick: the first child that is also third from the end must be in a list of three, and the sibling combinator reaches the rest. With :has(), the parent can now ask the question directly, which is much easier to read. More patterns like this are in the :has() guide.

The logical pseudo-classes: :is(), :where() and :not()

These three take selector lists as arguments and change both how you write selectors and how much they weigh.

/* Without :is(): six selectors */
.article h1 a, .article h2 a, .article h3 a,
.sidebar h1 a, .sidebar h2 a, .sidebar h3 a { color: inherit; }

/* With :is(): one */
:is(.article, .sidebar) :is(h1, h2, h3) a { color: inherit; }
  • :is() matches if any argument matches, and takes the specificity of its most specific argument.
  • :where() works exactly like :is() but always has zero specificity. Use it for defaults that anything should be able to override.
  • :not() matches if none of the arguments match. It accepts a list: button:not(.primary, .danger). Its specificity is that of its most specific argument.

Both :is() and :where() use forgiving selector lists. If one argument is invalid or unsupported, it is ignored and the others still work. A plain comma-separated list is not forgiving: one unknown selector drops the whole rule. That matters for vendor-prefixed pseudo-elements:

/* WRONG: Firefox does not know the WebKit selector, so it drops the whole rule */
input::-webkit-input-placeholder,
input::placeholder { color: gray; }

/* RIGHT: separate rules, or just use the standard one */
input::placeholder { color: gray; }

Note that pseudo-elements cannot go inside :is(), so for prefixed pseudo-elements you write separate rules. And :has() is deliberately unforgiving, so an invalid argument there also drops the rule.

Frequently Asked Questions

What are the four CSS combinators?

The descendant combinator (a space) matches any nested element, the child combinator (>) matches direct children, the next-sibling combinator (+) matches the element immediately after another, and the subsequent-sibling combinator (~) matches any later sibling with the same parent.

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

Both match an element if any selector in their list matches, and both ignore invalid arguments. The only difference is specificity: :is() takes the specificity of its most specific argument, while :where() always contributes zero, which makes it ideal for easily overridden defaults.

What is the difference between :nth-child() and :nth-of-type()?

:nth-child() counts every sibling element regardless of type, while :nth-of-type() counts only siblings with the same element name. Neither looks at classes; to count only elements with a class, use :nth-child(An+B of .class).

Do attribute selectors have higher specificity than classes?

No. Attribute selectors, classes and pseudo-classes all count in the same column, so [aria-current=”page”] has exactly the same specificity as .active.

Let the markup speak

Every attribute, every form state and every position in the tree is already information the browser has. Selectors are how CSS reads it. The fewer mirror classes you maintain, the fewer ways your visual state can lie. Once selection is under control, custom properties make the values those selectors apply just as maintainable.

Rule of thumb: before adding a state class, check whether an attribute or pseudo-class already describes that state.

Originally posted on 17 April 2025 and post last modified on 17 April 2025

Attribute Selectors CSS CSS Selectors Front-End Development Pseudo-Classes

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *