In CSS, :is()
is a functional pseudo-class that simplifies selector lists by grouping common parts, making your CSS more concise and maintainable. It selects any element that matches at least one of the selectors within its parentheses.
Detailed Explanation
The :is()
pseudo-class essentially acts as a shorthand for writing multiple selectors with a shared base. Before :is()
, you might have to repeat parts of a selector, which can become cumbersome, especially with more complex styles. :is()
avoids this repetition, leading to cleaner and easier-to-read CSS code. It's been widely supported across major browsers since early 2021.
Syntax
The basic syntax is:
:is(selector list) {
/* CSS rules */
}
Where selector list
is a comma-separated list of selectors.
Examples
Example 1: Styling Headings
Let's say you want to style all heading elements ( h1
, h2
, h3
, h4
, h5
, h6
) the same way. Without :is()
, you might write:
h1 {
color: blue;
font-family: sans-serif;
}
h2 {
color: blue;
font-family: sans-serif;
}
h3 {
color: blue;
font-family: sans-serif;
}
h4 {
color: blue;
font-family: sans-serif;
}
h5 {
color: blue;
font-family: sans-serif;
}
h6 {
color: blue;
font-family: sans-serif;
}
Using :is()
, you can simplify this to:
:is(h1, h2, h3, h4, h5, h6) {
color: blue;
font-family: sans-serif;
}
Example 2: Targeting Specific List Items
Imagine you want to style the first and last list items within an ordered or unordered list:
:is(ol, ul) :is(:first-child, :last-child) {
font-weight: bold;
}
This selector will apply the font-weight: bold
style to both the first and last list items in both ordered and unordered lists.
Example 3: Combining with other Pseudo-classes
:is()
can be nested and combined with other pseudo-classes:
article:is(:hover, :focus) p {
color: red;
}
This will turn the paragraph text red when the article
is either hovered over or receives focus.
Benefits
- Readability: Reduces repetition, making selectors more concise and easier to understand.
- Maintainability: Simplifies updating styles across multiple elements.
- Specificity: The specificity of the
:is()
pseudo-class selector is replaced by the specificity of the most specific selector in its argument list.
Conclusion
The :is()
pseudo-class is a valuable tool for writing cleaner, more maintainable CSS. By grouping common selector parts, it simplifies your stylesheets and improves readability. It's well-supported in modern browsers and is a great addition to any front-end developer's toolkit.