In this post, we'll take a look at :has() CSS selector real-world uses and how it can make your code better by reducing the amount of code you need to write.
First Case:
Have you ever created an interactive component that requires the ability to modify styles elsewhere on the page?
Suppose that we have a navbar with navigation items. Upon clicking a navigation item, a dropdown menu is displayed containing the relevant information.
Let's create it.
It is a common practice to modify the style of the navbar (e.g., change its height, color, opacity, etc...) and change the dropdown chevron related to the navigation item from "โ" to "โ" when displaying a dropdown.
I feel like I need to do this kind of stuff all the time.
As we know, It is not possible to directly modify the style of a parent selector from a child selector. Therefore, the old approach was to make this effect using JavaScript, as follows ๐
Within the function that toggles the dropdown "toggleDropDownMenu" we get the navbar element and change its color based on the dropdown's current state.
Whenever I implement something like this, I often find myself wondering if is it worth this hassle to just change color or height or whatever kind of style?
So, let's do some magicโจ
We will modify the navbar styles-set to be as follows:
We utilized the :has() selector to verify whether the "nav" contains an element with both the class names "dropdown" and "show" within its descendants. If such an element exists, it indicates that the dropdown is currently displayed. Consequently, the color of the navbar will be changed.
Here is the codepen for this case:
Second Case:
Assume we have a table of companies with their contacts and locations as follows:
Adding a colored hover effect to your table rows can be a nice UX improvement. Additionally, it helps your eyes keep track of which row you're on as you scan the table.
But what if the table only has one row? This effect sounds useless, right?๐ค
any solutions?
YES, exactly. we will use the :has() selector to decide whether we will add this hover effect to the table rows or not, depending on the number of rows.
This code snippet checks if the table has at least two rows (excluding the header), and applies the hover effect accordingly. If the table contains only one row, the effect is not applied.
Here is the codepen for this case:
And thus, we have explained two cases for using this awesome selector, It has ton of uses, You can utilize it in your own way.
Feel free to write your thoughts in the comments section๐๐ผ
Have a Good day.
Top comments (0)