Tailwind variants let you use Tailwind utilities under a specific condition. The syntax looks like this:
<div class="variant:utility">…</div>Each variant represents the condition. One example of such a condition is if a certain media query is present.
<div class="md:p-4">...</div>This causes the div to have 1rem of padding at the md breakpoint. So it’s equivalent to the following CSS:
@media screen and (width >= 768px) { div { padding: 1rem; }}Types of Variants
Tailwind has many built-in variants that include:
- Pseudo-classes, like
:hover,:focus,:first-child, and:required - Pseudo-elements, like
::before,::after,::placeholder - Media, Container, and feature queries, like breakpoints, dark mode, and
prefers-reduced-motion - Attribute selectors, like
[dir="rtl"]and[open] - Arbitrary variants
The most useful variants are:
- Media queries
- Container queries
- Arbitrary variants (for emergencies)
Arbitrary variants
Arbitrary variants are selectors — you can specify any CSS Selector for your variant to work. Here, & represents the element itself.
Examples:
[&>*]: selects all direct children elements&_*: selects all children elements
The rules for creating arbitrary variants are the same as those for creating arbitrary values — you have to replace spaces with underscores (or just don’t use spaces).
Arbitrary variants aren’t very useful because they look so complex. If you need to use them, you might want to use CSS directly instead.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson