Tailwind CSS hover and focus states


In Tailwind CSS, hover and focus states allow you to apply styles to elements when a user interacts with them, such as when they hover over an element with their mouse or focus on an element using the keyboard. This is useful for enhancing user experience and providing visual feedback.

1. Hover States

The hover variant in Tailwind CSS lets you apply styles when an element is hovered over. To use it, prefix the utility class with hover:. Here’s a basic example:

<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"> Hover over me </button>

In this example:

  • bg-blue-500 sets the initial background color.
  • hover:bg-blue-700 changes the background color to a darker blue when the button is hovered over.

2. Focus States

The focus variant in Tailwind CSS lets you apply styles when an element gains focus, such as when a user clicks on it or navigates to it using the keyboard. To use it, prefix the utility class with focus:. Here’s an example.

<input class="border border-gray-300 focus:border-blue-500 focus:outline-none p-2 rounded" type="text" placeholder="Focus on me">

In this example:

  • border-gray-300 sets the initial border color.
  • focus:border-blue-500 changes the border color to blue when the input field is focused.
  • focus:outline-none removes the default outline style when the input is focused.

3. Combining Hover and Focus States

You can also combine hover and focus variants to apply different styles for each interaction:

<button class="bg-green-500 hover:bg-green-700 focus:bg-green-800 text-white font-bold py-2 px-4 rounded"> Hover or Focus on me </button>

In this example:

  • bg-green-500 sets the initial background color.
  • hover:bg-green-700 changes the background color when hovered over.
  • focus:bg-green-800 changes the background color when focused.

4. Active and Visited States

Tailwind CSS also supports other interaction states such as active and visited:

  • Active State: Applied when an element is being activated, such as when a button is pressed. Use active: prefix:

    <button class="bg-red-500 active:bg-red-700 text-white font-bold py-2 px-4 rounded"> Press me </button>
  • Visited State: Applied to visited links. Use visited: prefix:

    <a href="#" class="text-blue-500 visited:text-purple-500"> Click me </a>

5. Customizing States

If you need to customize or extend the styles for these states, you can do so in the tailwind.config.js file. For example, you can add custom colors or other utilities:

module.exports = { theme: { extend: { colors: { 'custom-blue': '#1d4ed8', 'custom-green': '#065f46', }, }, }, }

With this configuration, you can use hover:bg-custom-blue or focus:bg-custom-green in your HTML.