0
0
Tailwindmarkup~5 mins

Focus-within variant in Tailwind

Choose your learning style9 modes available
Introduction

The focus-within variant helps style a parent element when any child inside it is focused. This makes it easier to highlight groups of inputs or sections when users interact with them.

Highlight a form section when a user clicks or tabs into any input inside it.
Change the border color of a card when a button or link inside it is focused.
Show a visual cue around a menu when any menu item inside is focused.
Improve accessibility by visually grouping related controls when focused.
Syntax
Tailwind
focus-within:<utility>

Use focus-within: before any Tailwind utility to apply styles when a child element is focused.

This variant works on the parent element, not the focused child itself.

Examples
The border of the div turns blue when the input inside is focused.
Tailwind
<div class="focus-within:border-blue-500 border-2 p-4">
  <input type="text" />
</div>
The background of the section changes to light gray when the textarea inside is focused.
Tailwind
<section class="focus-within:bg-gray-100 p-6">
  <textarea></textarea>
</section>
A ring appears around the nav when the link inside is focused.
Tailwind
<nav class="focus-within:ring-2 focus-within:ring-indigo-500">
  <a href="#">Link</a>
</nav>
Sample Program

This form container gets a blue glowing ring around it when any input inside is focused. This helps users see which form section they are working on.

Tailwind
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Focus-within Variant Example</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="flex items-center justify-center min-h-screen bg-gray-50">
  <form class="focus-within:ring-4 focus-within:ring-blue-400 border-2 border-gray-300 rounded-lg p-6 w-80">
    <label for="name" class="block mb-2 font-semibold">Name</label>
    <input id="name" type="text" class="w-full p-2 border border-gray-400 rounded focus:outline-none focus:ring-2 focus:ring-blue-600" placeholder="Enter your name" />
    <label for="email" class="block mt-4 mb-2 font-semibold">Email</label>
    <input id="email" type="email" class="w-full p-2 border border-gray-400 rounded focus:outline-none focus:ring-2 focus:ring-blue-600" placeholder="Enter your email" />
  </form>
</body>
</html>
OutputSuccess
Important Notes

The focus-within variant works well for grouping related inputs visually.

It improves keyboard navigation by showing focus on the container, not just the input.

Remember to use semantic HTML and labels for better accessibility.

Summary

focus-within styles a parent when any child inside is focused.

Use it to highlight form sections or groups of controls.

It helps users see where they are interacting on the page.