Search code examples
csssasstailwind-css

Any opposite of [&:not(.<class-name>)] in Tailwind / Plain CSS / SCSS? (Add class only if another specified class is attached to the element)


I have class="hover:[&:not(.ng-invalid)]:border-gray-500", which adds gray color to input border only when .ng-invalid class is not attached to that input while hovering over it.

Is there anything opposite of that, for example, I want to add this gray color, only when .ng-invalid is not attached and .ng-dirty is attached to the input, something like this:-

class="hover:[&:not(.ng-invalid)]:[&:has(.ng-dirty)]:border-gray-500"

for the replacement [&:has(.ng-dirty)] above, what should I write to check if .ng-dirty class is attached?

Please let me know if there are any plain css solutions too, that I should consider.


Solution

  • The feature of arbitrary variants is that anything inside the [] can be any CSS selector. So, in CSS, to assert an element has a class, we would use a class selector, like .ng-dirty. Thus, we can add this extra qualifier to your existing arbitrary variant selector so that :not(.ng-invalid) becomes :not(.ng-invalid).ng-dirty:

    hover:[&:not(.ng-invalid).ng-dirty]:border-gray-500
    

    <script src="https://cdn.tailwindcss.com/3.4.3"></script>
    
    <div class="hover:[&:not(.ng-invalid).ng-dirty]:border-gray-500 border h-10 m-2"></div>
    
    <div class="hover:[&:not(.ng-invalid).ng-dirty]:border-gray-500 ng-dirty border h-10 m-2"></div>
    
    <div class="hover:[&:not(.ng-invalid).ng-dirty]:border-gray-500 ng-dirty ng-invalid border h-10 m-2"></div>
    
    <div class="hover:[&:not(.ng-invalid).ng-dirty]:border-gray-500 ng-invalid border h-10 m-2"></div>