Using :has in Tailwind with adjacent sibling selectors

I have the following CSS, which works as intended.

[data-type="transfer"]:has(+ [data-type^='sale_']) {
  opacity: 0.25;
}

It looks at data attributes and will hide elements with data-type="transfer if they are adjacent to elements containing data attributes starting with “sale_”. For clarity, I reduced the opacity instead of hiding the element, to make things as clear as possible what I’m doing.

Here it is in a quick demo:

[data-type="transfer"]:has(+ [data-type^='sale_']) {
  opacity: 0.25;
}
<ul>
  <li data-type="transfer">a transfer</li>
  <li data-type="sale_buyer">a buyer sale</li>  
  <li data-type="transfer">a transfer</li>
  <li data-type="sale_seller">a seller sale</li>    
</ul>

How can I convert the working CSS above into Tailwind code now that :has is supported? I tried something like this, but it’s not working:

<li className="has-[[data-type="transfer"] + [data-type^="sale_"]]:hidden">...</li>

If you can work in reverse, Tailwind’s peer- would be better suited for this. (I didn’t even know you could use :has to target siblings; [data-type="transfer"] + [data-type^='sale_'] would be an equivalent CSS selector.)

Relevant class string:

opacity-25 peer peer-[[data-type=transfer]]:data-[type^=sale\_]:opacity-100

(Why sale\_ and not sale_? Underscores constitute as spaces in Tailwind and ordinarily need escaping, although in this instance omitting it does not change output for whatever reason.)

Generated CSS:

.opacity-25{
  opacity: 0.25
}

.peer[data-type=transfer] ~ .peer-\[\[data-type\=transfer\]\]\:data-\[type\^\=sale\\_\]\:opacity-100[data-type^=sale_]{
  opacity: 1
}

Tailwind Play demo

Edit 1: Didn’t account for the reversed nature of my reversed answer.

Edit 2: ~ is less strict than +, so this is not a perfect answer. Leaving up for posterity.

I ended up asking the creator of Tailwind how to do this and this is the answer he gave me. I was missing that first + inside the initial left bracket and this is the best answer.

<ul>
  <li class="has-[+[data-type^='sale\_']]:data-[type="transfer"]:opacity-25" data-type="transfer">a transfer</li>
  <li class="has-[+[data-type^='sale\_']]:data-[type="transfer"]:opacity-25" data-type="sale_buyer">a buyer sale</li>  
  <li class="has-[+[data-type^='sale\_']]:data-[type="transfer"]:opacity-25" data-type="transfer">a transfer</li>
  <li class="has-[+[data-type^='sale\_']]:data-[type="transfer"]:opacity-25" data-type="sale_seller">a seller sale</li>    
</ul>

Playground demo

Leave a Comment