Have you used the :is() selector to avoid repetition?
We all know how frustrating it can be to write repetitive and lengthy CSS rules when trying to style elements with similar characteristics. Well, today, I’m going to introduce you to a CSS selector that'll help you eliminate all that repetition and simplify your stylesheets - the :is() selector.
This issue is sponsored by Tailscan
Tailscan is a browser devtool for Tailwind CSS. It helps you build, design, and debug your Tailwind website visually in the browser. Tailscan offers autocompletion, config support, class validation, and visual guidelines. It also allows you to scan other Tailwind websites. With Tailscan, you'll instantly improve your development experience.
Now let's jump right in. 🌊
The Problem 🤔
Imagine you're working on a blog website that has different types of headings (h1, h2, h3) and lists (ul, ol) within both the main content area and the sidebar.
You want to apply the same set of styles to these elements, but only when they're inside the main content area or the sidebar. Without a proper selector, you would need to write multiple CSS rules, like this:
main h1,
main h2,
main h3,
main ul,
main ol,
aside h1,
aside h2,
aside h3,
aside ul,
aside ol {
text-transform: uppercase;
color: #65b;
}
This is super lengthy and unreadable.
The Solution 🔥
Enter the :is() selector! This powerful selector allows you to group multiple selectors into a single rule, significantly reducing code repetition and making your CSS more concise. Here's how you can rewrite the above example using the :is()
selector:
:is(main, aside) :is(h1, h2, h3, ul, ol) {
text-transform: uppercase;
color: #65b;
}
Much better, right?
Understanding the Syntax 🔍
The :is() selector takes a comma-separated list of selectors as its argument. The rule will apply to any element that matches at least one of the selectors within the parentheses.
In our example, the first :is(main, aside) targets both the main content area and the sidebar. The second :is(h1, h2, h3, ul, ol) targets headings and lists. By combining these two :is() selectors, we're applying the styles only to headings and lists within the main content area or the sidebar. That's a massive reduction in code complexity!
Now you know how to harness the power of the :is() selector to simplify your stylesheets and make your CSS more maintainable! Give it a try in your next project, and you'll see the difference it makes.
Until next time 👋
📘 I’m writing a new book!
If you loved this write-up and how it was explained, you’ll absolutely love my next eBook Level up with Tailwind CSS. Opened pre-orders in February and more than 150 people have grabbed it already 🤯 Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.