0
0
Tailwindmarkup~5 mins

Arbitrary variants for custom selectors in Tailwind

Choose your learning style9 modes available
Introduction
Arbitrary variants let you apply styles based on custom CSS selectors. This helps you style elements in special ways that Tailwind's default options don't cover.
You want to style an element only when a parent has a specific class.
You need to apply styles when an element is focused or hovered in a unique way.
You want to target elements based on attributes or states not included in Tailwind by default.
You want to write a quick custom selector without adding extra CSS files.
You want to style nested elements inside a component with a special condition.
Syntax
Tailwind
[&<custom-selector>]:<utility>
Use square brackets [] to wrap your custom selector inside the variant.
The ampersand & represents the current element in the selector.
Examples
Change background color to blue when the element is hovered.
Tailwind
[&:hover]:bg-blue-500
Make direct child paragraphs have red text.
Tailwind
[&>p]:text-red-600
Make the element bold if it has a data-active attribute set to true.
Tailwind
[&[data-active="true"]]:font-bold
Underline the element when it has the class 'custom-class'.
Tailwind
[&.custom-class]:underline
Sample Program
This example shows a button that changes background color when hovered using an arbitrary variant. The paragraph styles its first letter bigger and changes text color on hover using arbitrary variants.
Tailwind
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Arbitrary Variants Example</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="p-6">
  <button class="[&:hover]:bg-green-300 border border-gray-400 px-4 py-2 rounded">
    Hover me
  </button>
  <div class="mt-4">
    <p class="[&:first-letter]:text-4xl [&:hover]:text-purple-700">
      This paragraph uses arbitrary variants to style its first letter and text color on hover.
    </p>
  </div>
</body>
</html>
OutputSuccess
Important Notes
Arbitrary variants let you write any CSS selector inside Tailwind's variant syntax.
Remember to use the ampersand & to refer to the current element inside your selector.
Use this feature to keep your styles in one place without extra CSS files.
Summary
Arbitrary variants let you style elements using custom CSS selectors inside Tailwind.
Wrap your selector in square brackets and use & to refer to the element.
They help you handle special styling cases without writing separate CSS.