This is a guide on how to use arbitrary variants with @tailwindcss. Arbitrary variants are similar to arbitrary values, allowing you to create custom selector patterns that give you flexibility for styling specific elements.
- Arbitrary Values
- Arbitrary Variants
- Arbitrary Properties
- Using Arbitrary Variants
- External Resources
Arbitrary values are similar to arbitrary variants, but they are used to create custom values for your project. Of the two, arbitrary values are more common, used to assign custom values like text-[17px] for text size. Below is an an example of how to add arbitrary values to elements.
<p class="text-[17px]">My example body text.</p>For more details on arbitrary values, check out the @tailwindcss/docs.
π Note: It's possible to set an arbitrary value to any property, using
[and]to wrap the value.
Arbitrary variants in Tailwind CSS allow you to target specific elements using custom selectors. They are written using square brackets [ and ] and can contain any valid CSS selector.Below is an example of the syntax being used to target two separate elements.
<p class="[&]:flex [&>#a]:text-sm">
<p id="a">My example body text.</p>
</p>This is useful for applying styles to parent that have child elements, like in the case of a flex container with a child element. For more details on arbitrary variants, check out the @tailwindcss/docs.
π Note: The
>#syntax is used to target a child element, from&the current element, with a specificid.
Arbitrary properties are similar to arbitrary values, in that you can set a custom CSS property. Below is an example of how to set an arbitrary property to a custom value.
<p class="[--scroll-offset:56px]">My example body text.</p>For more details on arbitrary properties, check out the @tailwindcss/docs.
Here's an example of how to use arbitrary variants to apply different text sizes to specific elements based on their IDs:
<!DOCTYPE html>
<html>
<body class="[&>#a]:text-sm [&>#b]:text-lg">
<p id="a">My example body text.</p>
<p id="b">Another example body text.</p>
</body>
</html>In this example, we are selecting the child element with an id of a (by using [&>#a]), and then setting the text size to small (by using text-sm). The > child combinator in the selector indicates we want a direct child. Likewise, the # symbol is used to target an element with a specific id.
π Note: Some useful combinators include
+for adjacent siblings or~for all following siblings.
For more information about CSS selectors and combinators, check out the @w3school/css-selectors and @w3school/css-combinators references. If you're interested in learning more about arbitrary values, variants, and properties, check out the @tailwindcss/docs.
This gist is also available in a public repository created by the author ktortolini. Please, feel free to contact the author via email β ktortolini@smu.edu.