Responsive, Hover, and Focus Variants
Tailwind CSS allows you to conditionally apply utility classes based on screen size (responsive design), interaction state (like hover or focus), and more — using *variants*.
1. Responsive Variants
Prefix classes with breakpoints like sm:
, md:
, lg:
to apply styles at specific screen widths.
<div class="text-sm sm:text-base md: lg:text-xl"> Responsive Text Size </div>
This element will have increasing font size on larger screens.
2. Hover and Focus States
Tailwind includes variants for interaction states like hover:
, focus:
, active:
, and more.
<button class="bg-blue-500 hover:bg-blue-600 focus:ring-2 focus:ring-blue-400 text-white py-2 px-4 rounded"> Hover & Focus Me </button>
3. Group Hover Example
Use group
on the parent and group-hover:
on child elements:
<div class="group p-4 bg-gray-100 hover:bg-gray-200"> <h3 class="text-xl font-semibold group-hover:text-blue-600 dark:text-blue-400"> Hover to change heading color </h3> </div>
4. Combining Variants
You can combine responsive and state variants:
<button class="text-sm sm:text-base hover:bg-green-500 focus:outline-none focus:ring-2"> Responsive Button </button>
5. Customizing Available Variants
You can control which variants are generated in your tailwind.config.js
file:
// tailwind.config.js module.exports = { variants: { extend: { backgroundColor: ['active'], textColor: ['visited'], }, }, };
Conclusion
Responsive and interactive variants are a core strength of Tailwind. They enable powerful designs directly within your HTML, keeping your components both flexible and easy to maintain.