Course contentsShow
← Web Development
Lesson 636 of 2,98211. Utility-First CSS with TailwindFree lesson

Hover and Focus States

Using hover:, focus:, and focus-visible: prefixes to style interactive states without writing custom CSS.

Hover and Focus States

You'll learn how to style interactive elements when users hover over or focus on them using Tailwind's state prefixes—no custom CSS required.

The Core Idea

Interactive elements like buttons and links should respond visually when users interact with them. Tailwind provides state prefixes that let you apply styles conditionally based on user interaction:

  • hover: applies styles when the user's cursor hovers over an element
  • focus: applies styles when an element receives keyboard or programmatic focus
  • focus-visible: applies styles only when focus is visible (typically keyboard navigation, not mouse clicks)

Think of these prefixes like conditional decorators: "If this state is active, then apply this style."

How They Work

You chain a state prefix before any utility class using a colon. Tailwind automatically generates the proper CSS pseudo-classes (:hover, :focus, :focus-visible) behind the scenes.

<button class="bg-blue-500 hover:bg-blue-700 focus:ring-2">
  Click Me
</button>

In this button:

  • Normally: blue background (bg-blue-500)
  • On hover: darker blue (hover:bg-blue-700)
  • When focused: adds a 2px ring (focus:ring-2)
<input 
  class="border-gray-300 focus:border-blue-500 focus-visible:ring-2"
  type="text"
/>

This input changes border color on focus and adds a ring only when focus is keyboard-driven (not from mouse clicks).

Why focus-visible Matters

focus-visible: respects browser heuristics about when focus indicators should appear—improving both accessibility and aesthetics. Users navigating by keyboard see clear indicators; mouse users see cleaner interfaces.

Key Takeaway: Tailwind's hover:, focus:, and focus-visible: prefixes let you create responsive, accessible interactive states by simply adding prefixes to utility classes—no CSS file needed.