Content filtering with CSS :has() selector
The :has()
selector is a relatively new addition to CSS that allows you to target elements that contain specific content. This is a significant departure from traditional CSS selectors, which target elements based on their structure or attributes. By targeting elements based on their content, you can build content filters, interactive menus, and more. However, it’s essential to be aware of browser compatibility issues and provide fallbacks when necessary.
Basic syntax
The basic syntax of the :has()
selector is as follows:
element:has(selector) {
/* CSS rules */
}
Here, element
represents the parent element you want to target, and selector
is the content you want to look for within that parent element.
Working example
With the :has()
selector, you can style and display only parts that contain specific category tags without the need for JavaScript.
<body>
<main>
<div class="filters">
<input type="checkbox" id="a-team-filter" checked>
<label for="a-team-filter">Team A</label>
<input type="checkbox" id="b-team-filter" checked>
<label for="b-team-filter">Team B</label>
</div>
<ol>
<li class="a-team">John</li>
<li class="b-team">Robert</li>
<li class="b-team">Donald</li>
<li class="a-team">Rupert</li>
</ol>
</main>
</body>
Adding filtering functionality to our checkboxes is straightforward, thanks to the use of these two CSS selectors:
body:has(#b-team-filter:not(:checked)) .b-team {
display: none;
}
body:has(#a-team-filter:not(:checked)) .a-team {
display: none;
}
Codepen demo: https://codepen.io/ronaldsvilcins/pen/rNormMJ.
Enjoyed this post? Please grab the RSS feed. You can also buy me a coffee.