I want to focus a div
surrounding a button but only when keyboard focused. Usually focus-within
works, but in this case it should only focus on keyboard focus (focus-visible:
) and not when clicking with the mouse(focus:
).
Essentially, I need to combine focus-within
and focus-visible
. How can this be done?
Tailwind Play: https://play.tailwindcss.com/ApDB5gSjqv
<div class="flex h-screen items-center justify-center">
<div class="rounded-lg bg-green-100 px-20 py-20 focus-within:ring-4 focus-within:ring-blue-300">
<button class="bg-green-200 px-6 py-3 focus:outline-none">Focusable Button</button>
</div>
</div>
Notes:
- Based on this thread, it looks like w3c doesn’t have support for
focus-within-visible
. What’s an alternative or round-about way to achieve this? - It looks like there is support for
:has(:focus)
selector in some browsers but how should this be applied in Tailwind…? Source
>Solution :
Instead of using focus-within you could add relative
to the div you want to make look focused with the ring. Then make the button a peer
and have an absolutely positioned div after it use the peer-focus-visible
modifier to add any "focused" styles you want.
EDIT: You’ll need to make the div be behind the button by adding relative to the button and assigning an appropriate z-index value to both the inset div and button.
<div class="flex h-screen items-center justify-center">
<div class="rounded-lg bg-green-100 px-20 py-20 relative">
<button class="bg-green-200 px-6 py-3 focus:outline-none peer relative z-[1]">Focusable Button</button>
<div class="absolute inset-0 rounded-lg peer-focus-visible:ring-4 peer-focus-visible:ring-blue-300 z-[0]"></div>
</div>
Here is an edited example on Tailwind Play https://play.tailwindcss.com/us5kpJg6cV