skip to Main Content

I am having a difficult time trying to style a td element which has a div that has a class called ‘check’ as its child element. I am trying to style it from div element which is the parent of the table.

This is my selector in the below example:

<div class="[&>table>tbody>tr>td:has-[ .check]]:bg-gray-100">
  <table>
    <thead>...</thead>
    <tbody>
      <tr>
        <td><div class="check">...</div></td>
      </tr>
    </tbody>
  </table>
</div>

I am not that fluent with tailwind. What is it that I am doing wrong and how can I fix it

I’ve tried achieving this using the has- modifier
https://tailwindcss.com/docs/hover-focus-and-other-states#styling-based-on-descendants

2

Answers


  1. Updated Answer

    While you cannot style a parent depending on the children by :has-[.CLASS], you can do so by javascript.

    document.querySelectorAll('.table-container td').forEach(td => {
      td.querySelector('.check') && td.classList.add('bg-gray-100');
    });
    <script src="https://cdn.tailwindcss.com"></script>
    <div class="table-container">
      <table>
        <thead>...</thead>
        <tbody>
          <tr>
            <td><div class="check">This one will be highlighted</div></td>
            <td><div>This one NOT!</div></td>
          </tr>
        </tbody>
      </table>
    </div>

    Orginal Answer

    You cannot select a class with the has-{modifier}, you can only select an element by either a pseudo-class or by the tag name.

    As per TailwindCSS

    You can use has-* with a pseudo-class, like has-[:focus], to style an element based on the state of its descendants. You can also use element selectors, like has-[img] or has-[a], to style an element based on the content of its descendants.

    However, you can achive that without has-* simply by selecting the element with .check class like the following:

    <script src="https://cdn.tailwindcss.com"></script>
    <div class="[&>table>tbody>tr>td>.check]:bg-gray-100">
      <table>
        <thead>...</thead>
        <tbody>
          <tr>
            <td><div class="check">...</div></td>
          </tr>
        </tbody>
      </table>
    </div>
    Login or Signup to reply.
  2. I think has-[>table>tbody>tr>td>.check]:bg-gray-100 is what you need.

    Tailwind Playground

    Update

    To target the td parent of .check.

    <td class="has-[>.check]:bg-gray-100"><div class="check">...</div></td>

    Tailwind Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search