Introduction
As your CSS grows, selectors become harder to manage. Advanced CSS selectors like :is(), :where(), and :has() help you write cleaner, shorter, and more scalable CSS.
In this chapter, you will learn:
- Grouping selectors with
:is()and:where() - Parent selection with
:has()(a game-changer) - Dynamic calculations using
calc() - Advanced attribute and structural selectors
Grouping Selectors: :is() vs :where()
Both selectors connect multiple items, but they handle specificity differently.
:is() (Takes Highest Specificity)
/* Before */
.card h1, .card h2, .card h3 { margin-bottom: 10px; }
/* After (Cleaner) */
.card :is(h1, h2, h3) { margin-bottom: 10px; }:where() (Zero Specificity)
Useful for resets and base styles that should be easily overridden.
:where(h1, h2, h3) { font-family: Arial; }The Parent Selector: :has()
:has() allows you to style a parent element based on its children.
/* Style card if it contains an image */
.card:has(img) { padding-top: 0; }
/* Highlight form group if input is invalid */
.form-group:has(input:invalid) { border-color: red; }:has() is supported in all modern browsers but check compatibility for older versions.Calculations with calc()
Perform math directly in CSS. Great for responsive layouts.
.container {
width: calc(100% - 40px);
}
/* Mixing with variables */
.box {
width: calc(100% - var(--gap));
}Advanced Attribute Selectors
| Syntax | Meaning | Example |
|---|---|---|
[attr^="val"] | Starts with | a[href^="https"] |
[attr$="val"] | Ends with | a[href$=".pdf"] |
[attr*="val"] | Contains | a[href*="login"] |
Common Beginner Mistakes & Best Practices
Common Mistakes
- Overusing
:has()leading to performance issues - Creating unreadable widely-nested selectors
- Ignoring browser support for new features
Best Practices
- Use
:where()for utility classes (low specificity) - Use
calc()for fluid sizing - Keep selectors flat and readable
Chapter Summary
In this chapter, you learned:
- How
:is()and:where()simplify selector grouping. - How to use
:has()to style parents based on children. - Using
calc()for dynamic property values. - Advanced attribute selectors for links and inputs.
You now understand modern CSS selector power and how professionals write cleaner stylesheets.