Targetting next sibling on hover with tailwindcss

Viewed 1067

I am trying to hide an element until its previous sibling is hovered over, in css (or scss rather), it looks like this:

.menu-container {
  // style with flex etc...
  & .menu-item-link {
    // style the link...
    &+.sub-menu-container {
      display: none;
    }
    &:hover+.sub-menu-container {
      display: block;
    }
  }
}
<ul class="menu-container">
  <li class="menu-item-container">
    <a class="menu-item-link">Ingredients</a>
    <ul class="sub-menu-container">
      <li class="sub-menu-item-container">
        <a class="sub-menu-link">Fruits</a>
      </li>
      <li class="sub-menu-item-container">
        <a class="sub-menu-link">Vegetables</a>
      </li>
      <li class="sub-menu-item-container">
        <a class="sub-menu-link">Dairy</a>
      </li>
      <li class="sub-menu-item-container">
        <a class="sub-menu-link">Children</a>
      </li>
    </ul>
  </li>
</ul>

How do I achieve this using tailwind?

1 Answers

You're not actually trying to target a sibling in your code, you're trying to target a child element. This is a very simple process when you just want to show a sub-menu dropdown.

Just add group to the hover trigger (.menu-item-link in your case) and group-hover:[some-display-class] to the child. This way the child will change it's display property when the parent element (or itself) is hovered.

You should change your title, also I'd recommend that you don't use Tailwind with class names like that. Please see extracting components for the recommended way to use Tailwind CSS. Of course, you are free to use it how you want but you're better off with plain old CSS if you want to use SCSS and classes like that.

Example with your structure:

<ul>
  <li class="group">
    <a>Ingredients</a>
    <ul class="hidden group-hover:block">
      <li>
        <a>Fruits</a>
      </li>
      <li>
        <a>Vegetables</a>
      </li>
      <li>
        <a>Dairy</a>
      </li>
      <li>
        <a>Children</a>
      </li>
    </ul>
  </li>
</ul>

Example on Tailwind Play https://play.tailwindcss.com/dFc2zlmqDA

Related