skip to Main Content

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 on white, to black on white.

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.

2

Answers


  1. I think you can use the arbitrary variants feature in Tailwind CSS 3.1 to style nested elements based on the parent class.

    <div class="bg-white [&> .text-white]:not([class*='bg-']):text-black">
      <p class="text-white">This text will be black</p>
      <p class="text-white bg-red-500">
        This text will be white with red background
      </p>
    </div>
    

    I hope this helps you with your problem.

    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search