Course contentsShow
← Web Development
Lesson 455 of 2,9828. Advanced CSS Selectors and FeaturesFree lesson

Combining Modern Pseudo-Classes

Chain :is(), :has(), :not(), and other modern selectors to create powerful, readable selection patterns.

Combining Modern Pseudo-Classes

You'll learn how to chain and combine modern pseudo-classes to create powerful, expressive selectors that target exactly what you need.

Now that you've learned individual modern pseudo-classes like :is(), :has(), :not(), :focus-visible, :focus-within, and others, it's time to unlock their true potential: using them together.

The Power of Combination

Think of pseudo-classes as LEGO blocks—individually useful, but incredibly powerful when snapped together. By chaining multiple modern selectors, you can create sophisticated selection patterns that would otherwise require verbose, repetitive CSS or even JavaScript.

How Combining Works

You can combine pseudo-classes by simply writing them one after another, or by nesting them within each other:

/* Target valid inputs that are NOT empty and have focus */
input:valid:not(:placeholder-shown):focus-visible {
  border-color: green;
}

/* Style a container that HAS a focused child, 
   but NOT when that child is a button */
.card:has(:focus-visible:not(button)) {
  box-shadow: 0 0 0 3px blue;
}

/* Target any section that has an invalid input 
   AND is within a focused container */
section:focus-within:has(:invalid) {
  background-color: #fff3cd;
}

Real-World Example

/* Highlight forms with validation errors, 
   but only if the user has interacted */
form:has(input:user-invalid:not(:focus)) {
  border-left: 4px solid red;
}

This targets a form containing an invalid input that the user has touched but isn't currently focused on—perfect for showing persistent error indicators without annoying the user mid-typing.

Key Takeaway: Combining modern pseudo-classes lets you write precise, readable selectors that respond to complex conditions—making your CSS more maintainable and reducing the need for extra classes or JavaScript.