Let's say I want all the links inside white card to be black, and all the links inside orange cards to be white. I can easily do in pure CSS:
.card--primary {
background-color: white;
a {
color: black
}
}
.card--danger {
background-color: orange;
a {
color: white;
}
}
But how can I achieve similar behaviour using Tailwind (or other CSS utility frameworks)?
This is possible in tailwind 3.1 with the addition of the arbitrary variants feature. The way you would do this is by using a selector on the parent div:
<div className="card--primary bg-white [&>a]:text-black" >
<a/>
<a/>
<div/>
<div className="card--danger bg-orange [&>a]:text-white" >
<a/>
<a/>
<div/>
In case of Tailwind CSS
Read the descriptive and a very brief documentation entry here: Using arbitrary variants.
As I can see you need to change the color of all the <a>
links no matter how deeply they reside in the <cards>
. Use an underscore between &
and a
selectors - [&_a]:text-black
. This translates to:
.card--primary {
/* arbitrarily nested <a> links */
a {
color: black
}
}
On the other hand the Tailwind directive with >
between &
and a
=> [&>a]:text-black
would result in this css (only the direct child <a>
nodes would be styled):
.card--primary {
/* direct-child <a> links */
> a {
color: black
}
}
Recap: the resulting Tailwind HTML for your case:
<div className="card--primary [&_a]:text-black" >
<a></a> !-- will be black
<div>
<a></a> !-- will be black
</div>
<div/>
<div className="card--danger [&_a]:text-white" >
<a></a> !-- will be white
<div>
<a></a> !-- will be white
</div>
<div/>
That's it. I hope it is helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With