How to Use :is() Selector in CSS for Cleaner Code
The CSS
:is() selector lets you group multiple selectors inside one rule, so you can write cleaner and shorter code. It matches any element that fits at least one of the selectors inside the parentheses. Use it like :is(selector1, selector2, ...) to apply styles to all those selectors at once.Syntax
The :is() selector takes a comma-separated list of selectors inside parentheses. It matches any element that matches any of those selectors.
:is(selector1, selector2, ...): Matches elements matching selector1 or selector2 or others.- Selectors inside can be simple or complex (like classes, IDs, element types, pseudo-classes).
css
:is(selector1, selector2, selector3) { /* styles */ }Example
This example shows how to style all <h1>, <h2>, and elements with class .highlight using one rule with :is().
css
h1, h2, .highlight {
color: darkblue;
font-weight: bold;
}
/* Using :is() to simplify */
:is(h1, h2, .highlight) {
color: darkblue;
font-weight: bold;
}Output
All <h1>, <h2>, and elements with class 'highlight' appear bold and dark blue in the browser.
Common Pitfalls
Some common mistakes when using :is() include:
- Using
:is()with only one selector, which is unnecessary. - Not separating selectors inside
:is()with commas. - Expecting
:is()to match elements that match all selectors inside it (it matches any one). - Using
:is()in very old browsers that do not support it (modern browsers support it well).
css
/* Wrong: missing commas inside :is() */ :is(h1 h2) { color: red; } /* Correct: commas separate selectors */ :is(h1, h2) { color: red; }
Quick Reference
Tips for using :is() selector:
- Use it to group selectors and reduce repetition.
- Works well with pseudo-classes like
:hoveror:focus. - Improves readability and maintainability of CSS.
- Supported in all modern browsers.
Key Takeaways
Use
:is() to group multiple selectors and apply styles in one rule.:is() matches elements that fit any selector inside its parentheses.Separate selectors inside
:is() with commas for correct syntax.Avoid using
:is() with only one selector as it adds no benefit.Modern browsers support
:is(), making your CSS cleaner and easier to read.