In this trick, we will learn about CSS :is() and :where() pseudo-classes functions and how it works. We also look into how it’s a smart way to handle multiple elements in design.
CSS :is() Pseudo-class Function
The :is()
pseudo-class is like a magic wand for selecting elements that match any of the provided selectors. It’s a time-saver when you want to apply the same styles to multiple elements without repeating yourself.
:is() Function Example
Let’s have an example of :is() function to understand it in a better way. Let’s say you have a bunch of anchors (<a>
) selectors who are the child of many. But you only want to target the a
elements that are children of ul li
, ol li
, and p
and give them all the same font style. Instead of writing separate rules for each, you can use :is() function. See the following example.
Normal selectors
ul li a, ol li a, p a { color: blue }
Using :is() function
:is(ul, li, p) a { color: blue }
The above code will work the same as you normally do in CSS. You can implement it as you want accordingly selectors.
CSS :where() Pseudo-class Function
The :where()
function is another gem in the CSS toolkit. It allows you to apply styles to elements based on a condition, irrespective of their position in the document tree. It’s incredibly handy when you need to style elements dynamically without worrying about their hierarchy.
:where() Function Example
Let’s say you want to style headings h1
, h2
, and h3
within articles differently. Instead of targeting them individually, you can use :where() to apply styles to all headings within that article. See the following example.
Normal selectors
article h1, article h2, article h3 { color: blue }
Using :where() function
article :where(h1, h2, h3) { color: blue }
With :where(), you can keep your CSS concise and maintainable, even as your HTML structure evolves.
Putting :is() and :where() Together
You can also use these pseudo-classes functions together to target more specific elements. Let’s combine :is() and :where() to see the magic happen. Imagine you have a navigation menu where you want to highlight the current page link and style all links uniformly. Here’s how you can do it.
nav ul :is(li:where(.active), li:hover) a { color: #ffcc00; /* Yellow color for active and hovered links */ text-decoration: underline; }
This code selects the active link and also applies styles to hovered links, ensuring a consistent user experience.
More Tricks
FAQs
:is() selects elements matching any of the provided selectors, while :where() applies styles based on conditions, regardless of the document hierarchy.
Simply incorporate :is() to target multiple elements with shared styles and utilize :where() to apply styles dynamically based on conditions, enhancing code efficiency.