CSS :has selector and Tailwind support
What is a CSS :has selector?
The new CSS selector :has helps us to target previously hard-to-select HTML elements in a DOM.
:has selector belongs to CSS Baseline 2023 and is supported by major browsers (Chrome, Safari, Firefox, and Edge)
For example, it is easy to paint the background of the <p> tag with simple CSS:
HTML:
<div>
<p>123</p>
</div>
<div>
ABC
</div>
CSS:
div p {
background-color: #cbd5e1;
}
Output:
But, it is impossible to paint the background of it's parent <div> tag without changing the HTML code.
We have to modify code
We have to add some identifier like .with-bg to the parent <div> to paint the background.
HTML:
<div class="with-bg">
<p>123</p>
</div>
<div>
ABC
</div>
CSS:
div.with-bg {
background-color: #cbd5e1;
}
Output:
When we cannot change HTML
However, we sometimes do not have the freedom to modify the HTML code.
The has selector can be the solution for such cases.
With the has selector, we can paint the background of the parent <div> tag without modifying the HTML. We update the CSS rule like this:
HTML:
<div>
<p>123</p>
</div>
<div>
ABC
</div>
CSS:
div:has(p) {
background-color: #cbd5e1;
}
Output:
We updated the CSS rule but did not change the HTML code. The has selector allows us to select the parent of the <p> tag, which does not have an ID nor a class. The has selector is like a parent selector.
Less ID and classes
With the has selector, we can target HTML elements with less identifiers - IDs and classes. This will lead to less amount of HTML code.
Partial support in TailwindCSS
Tailwind has 'utility classes' such as:
:hover
:focus
:first-child
Currently, this utility is NOT available yet:
:has
However, we can still use has with Tailwind's square bracket notation .
HTML:
<div class="[&:has(p)]:bg-slate-300">
<p>123</p>
</div>
<div class="[&:has(p)]:bg-slate-300">
ABC
</div>
Output with developer tools:
The above square bracket notation produces this CSS rule:
.\[\&\:has\(p\)\]\:bg-slate-300:has(p) {
--tw-bg-opacity: 1;
background-color: rgb(203 213 225 / var(--tw-bg-opacity));
}