One of the most essential skills you need to learn here is to create simple Tailwind utilities, because:
- Tailwind’s utilities are not just “utilities”
- They’re more like mixins — powerful and useful tools that let you replicate code quickly
This is a little-known fact because Tailwind has packaged their “utilities” as almost a 1-1 mapping to a CSS value (like p is for padding).
We’re going to unpack this quite a bit and you’ll begin to see the powers behind Tailwind utilities. You’ll also see the gotchas and how to work around them.
Anatomy of a Utility
Writing a utility is similar to writing a CSS Selector. Except you define a Tailwind utility by using the @utility at-rule
@utility vertical { /* CSS properties go here */ display: flex; flex-flow: column; gap: 1rem;}That’s it.
Once you have defined this utility, you can use it anywhere in your HTML directly — and the relevant CSS properties will be added to that element.
<div class="vertical"> <h1>Hello</h1> <p>This is a vertical layout</p></div>Hello
This is a vertical layout
Tailwind utilities can also take in CSS variables — this allows you to create very simple utilities with powerful effects.
@utility grid-simple { display: grid; grid-template-columns: repeat(var(--cols), minmax(auto, 1fr)); /* Other CSS properties */}Once I have defined grid-simple, I can use it like this:
<div class="grid-simple [--cols:2]"> <div class="bg-blue-300 p-2 text-center">Item 1</div> <div class="bg-blue-300 p-2 text-center">Item 2</div></div>In the example above, I no longer worry about preventing grid blowouts because it’s handled by grid-simple. And I can just change the --cols value at different breakpoints to get the layout I want.
Using Tailwind Utilities in CSS
You can use the Tailwind utilities you create in CSS with the @apply rule. The following is an extremely crude example with the utilities we mentioned above, but imagine this:
.grid-article { @apply grid-simple; --cols: 1;
@media (width >= 800px) { --cols: 2; }}Resize your browser to see this work
If you use Tailwind breakpoint variants, you don’t even have to write a @media query rule. Imagine the following.
.grid-article { @apply vertical; @apply md:grid-fr-auto;}This says: Use vertical on mobile and switch to grid-fr-auto at 768px.
- Use a
verticallayout on mobile - And switch to
grid-fr-autoon tablet
Resize your browser to see this work
This is super convenient!
I’ll talk more about these techniques in the Layouts section.
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