Dealing with CSS :focus selector on iOS Safari

2022-09-28

daisyUI provides a Dropdown component which uses the :focus selector to determine whether the dropdown-content is opened.

<body>
  <div class="flex w-screen h-screen justify-center items-center">
    <div class="dropdown dropdown-right">
      <label tabindex="0" class="btn m-1">Click</label>
      <ul
        tabindex="0"
        class="dropdown-content menu p-2 shadow bg-base-100 rounded-box w-52"
      >
        <li><a>Item 1</a></li>
        <li><a>Item 2</a></li>
      </ul>
    </div>
  </div>
</body>

However, after opening the dropdown on iOS Safari, it is not possible to close the dropdown by touching out of the button.

The reason is the body or parent element cannot replace the dom being focused, to fix this problem we need to add a tabindex="0" attribute to body or parent element.

<body>
- <div class="flex w-screen h-screen justify-center items-center">
+ <div class="flex w-screen h-screen justify-center items-center" tabindex="0">
    <div class="dropdown dropdown-right">
      <label tabindex="0" class="btn m-1">Click</label>
      <ul
        tabindex="0"
        class="dropdown-content menu p-2 shadow bg-base-100 rounded-box w-52"
      >
        <li><a>Item 1</a></li>
        <li><a>Item 2</a></li>
      </ul>
    </div>
  </div>
</body>

The problem is solved. 🎉

🎉  Thanks for reading and hope you enjoy it. Feel free to check out my other posts and find me on X and GitHub!