Hover Focus Active States in TailwindCSS
? Hover, Focus, and Active States in Tailwind CSS
Tailwind makes it simple to style elements for different interaction states using state variants like hover:, focus:, and active:.
How It Works
Prefix any utility class with a state to apply styles only when the element is in that state.
Syntax:
<state>:<utility-class>
Common States
| State | Description | Example Prefix |
|---|---|---|
| Hover | When the mouse is over an element | hover: |
| Focus | When the element has keyboard focus | focus: |
| Active | When the element is being clicked/pressed | active: |
| Disabled | When the element is disabled | disabled: (requires plugin or custom styles) |
Examples
1. Change background color on hover
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"> Hover me</button>Normal: blue background
On hover: darker blue background
2. Change border color on focus (good for accessibility)
<input class="border border-gray-300 focus:border-blue-500 focus:outline-none" type="text" placeholder="Focus me" />Normal: gray border
On focus: blue border, no default outline
3. Change opacity on active (when pressing)
<a href="#" class="opacity-90 active:opacity-50"> Press me</a>Normal: 90% opacity
While pressed: 50% opacity
4. Multiple states combined
<button class="bg-green-500 hover:bg-green-600 focus:ring-4 focus:ring-green-300 active:bg-green-700 text-white px-5 py-2 rounded"> Submit</button>On hover: background darkens
On focus: ring appears
On active (click): background darkens more
Using Transitions with States
To smooth the effect between states, combine with transition utilities:
<button class="bg-purple-500 hover:bg-purple-700 transition-colors duration-300 text-white px-4 py-2 rounded"> Smooth hover</button>Summary
| Prefix | Effect |
|---|---|
hover: | Style on mouse hover |
focus: | Style on keyboard focus |
active: | Style when clicking/pressing |
focus-visible: | Style when element is focused and visible (accessibility) |
If you want examples for styling disabled states, visited links, or more complex interactions, just ask!