The :is()
pseudo-class, also known as the "matches-any" pseudo-class, takes a selector list as its argument and selects any element that can be selected by one of the selectors in that list. It's a powerful tool for writing more compact and readable CSS, especially when dealing with complex selector chains.
Example 1: Grouping Selectors
/* Selects any <h1>, <h2>, or <h3> element inside an <article> */
article :is(h1, h2, h3) {
color: darkcyan;
}
Explanation
Instead of writing three separate rules (article h1
, article h2
, article h3
), :is()
allows you to group these selectors into a single, more maintainable rule. This makes your CSS cleaner and easier to read.
Example 2: Simplifying Complex Lists
/* Selects any element with class 'important' or 'urgent' that is a direct child of a <div> or a <section> */
:is(div, section) > :is(.important, .urgent) {
font-weight: bold;
}
Explanation
The :is()
pseudo-class is excellent for simplifying complex combinations of selectors. This code bolds elements with the class important
or urgent
if they are a direct child of either a <div>
or a <section>
.
Example 3: Styling Links in Different States
/* Applies styles to a link when it is being hovered over or is in focus */
a:is(:hover, :focus) {
text-decoration: none;
color: red;
}
Explanation
This example is a common use case for :is()
. It removes the underline and changes the color of an anchor tag <a>
when the user either hovers their mouse over it or focuses on it using their keyboard.
Example 4: Targeting Form Elements
/* Adds a border to various input types */
:is(input[type="text"], input[type="email"], textarea) {
border: 2px solid #ccc;
}
Explanation
Here, :is()
is used to apply a consistent border style to different types of form fields. This is more efficient than creating a separate rule for each input type.
Example 5: Nested Selectors
/* Styles any <p> or <span> that is a descendant of a <header> or <footer> */
:is(header, footer) :is(p, span) {
font-size: 0.9rem;
}
Explanation
This demonstrates the power of nesting :is()
pseudo-classes. It efficiently targets <p>
and <span>
elements that are located anywhere inside a <header>
or <footer>
element.
Example 6: Applying Grid or Flex Properties
/* Makes elements with these classes flex containers */
:is(.card-container, .profile-gallery) {
display: flex;
gap: 1rem;
}
Explanation
When you have multiple containers that should share the same layout properties, :is()
can simplify your CSS. This rule applies display: flex
and a gap
to elements with either the card-container
or profile-gallery
class.
Example 7: General Element Styling
/* Styles various text-level elements within a main content area */
main :is(p, li, blockquote) {
line-height: 1.6;
}
Explanation
This selector applies a specific line-height
to paragraphs, list items, and blockquotes that are within the <main>
element of a webpage, ensuring consistent text spacing in the primary content area.