I am trying to do some fancy auto-color contrast correction work. I use Tailwind, and am trying to create some CSS rules that automatically change the color when the contrast is too low.
Assume the following:
.bg-white .text-white {
color: black;
}
Easy. We automatically change white text on a white background, into black text on a white background. Whenever someone specifies .text-white
, they no longer have to worry that another background color specified higher up out of their control, is going to break the WCAG Accessibility guidelines.
This is where our problem begins however. The following HTML will render the white text illegible:
<div class="bg-white">
<div class="bg-black">
<span class="text-white">I was legible until you tried to be smart.</span>
</div>
</div>
There are many ways I could solve this conundrum; but what I want to know, is if there is a way to achieve this with the :has() selector.
I would like something like the following:
.bg-white:not(:has(class*="bg-")) .text-white {
color: black;
}
I'm hoping that I am saying "Select any text-white which is inside a bg-white, which does not have any other elements with a class similar to "bg-" because this would change the background color.
My goal is to make it so that only the most immediate class which changes color is presumed to be the background color.
You are almost good. You are missing the []
.bg-white:not(:has([class*="bg-"])) .text-white {
color: red;
}
<div class="bg-white">
<div class="bg-black">
<span class="text-white">I was legible until you tried to be smart</span>
</div>
</div>
<div class="bg-white">
<span class="text-white">I was legible until you tried to be smart.</span>
</div>