Search code examples
htmlcsstailwind-css

TailwindCSS: peer-has-[] only work for siblings with peer class appearing before the peer-has-[] element


I want to style an element based on a class appearing in the descendants of a sibling element. I am able to achieve that if the sibling element happens to appear before the element to be styled in the HTML code, but it does not work if the sibling appears right after it.

Here's a sample code

<div>
  <div class="peer/before">
    <div class="active"></div>
  </div>
  <h1 class="peer-has-[.active]/before:italic">This works!</h1>
</div>

<div>
  <h1 class="peer-has-[.active]/after:italic">This does not!</h1>
  <div class="peer/after">
    <div class="active"></div>
  </div>
</div>

Here's a stackblitz to reproduce this


Solution

  • The peer-* variants by their very nature only work for elements before the class with the peer-* modifier attached. This is because peer relies on the CSS subsequent-sibling combinator ~.

    If you need to rely on some element after, you could consider using a has-* variant instead like:

    <script src="https://cdn.tailwindcss.com/3.4.1"></script>
    
    <div>
      <h1 class="has-[+.after_.active]:italic">This does not!</h1>
      <div class="after">
        <div class="active"></div>
      </div>
    </div>
    
    <div>
      <h1 class="has-[+.after_.active]:italic">This does not!</h1>
      <div class="after">
        <div></div>
      </div>
    </div>