tailwind-cssfocus

Keep div visible when interacting with items inside it


This works insofar as the links show correctly when the input is in focus. Is there a way I can get the visible status to remain when a link is clicked? At the moment, the focus changes immediately so the div disappears.

<div class="group p-8">
  <input type="text" class="peer bg-white w-full px-4 py-2 border-2 border-gray-200">
  <div class="group-focus-within:visible invisible relative">
    <ul class="max-h-40 w-full absolute z-50 bg-gray-50 border-2 border-gray-200 rounded divide-y-2 divide-gray-100 overflow-y-scroll shadow-lg px-4 py-2 -mt-px">
      <li class="py-2">
        <a href="#">Link 1</a>
      </li>
      <li class="py-2">
        <a href="#">Link 2</a>
      </li>
      <li class="py-2">
        <a href="#">Link 3</a>
      </li>
      <li class="py-2">
        <a href="#">Link 4</a>
      </li>
      <li class="py-2">
        <a href="#">Link 5</a>
      </li>
    </ul>
  </div>
</div>

Play here: https://play.tailwindcss.com/S7kFqSe9wF


Solution

  • You can achieve that by making the div containing the links remains visible when any of its child links are clicked.

    1. Add a tabindex to the parent div: This makes the div focusable, allowing it to maintain focus when a child element is clicked.
    2. Use :focus-within on the parent div: This will ensure that the div remains visible as long as any of its child elements are focused.

    https://play.tailwindcss.com/BE52iMzLj1