In this tutorial, our goal is to learn how to use the @apply
directive in Tailwind CSS for extracting common utility patterns into reusable classes. This is a powerful technique that can help maintain clean, manageable, and DRY ("Don't Repeat Yourself") stylesheets.
By the end of this tutorial, you will be able to:
- Understand the @apply
directive in Tailwind CSS
- Extract common utility patterns into reusable classes
- Maintain cleaner and more manageable stylesheets
Prerequisites: A basic understanding of HTML, CSS, and Tailwind CSS is required to follow along with this tutorial.
The @apply
directive in Tailwind CSS allows you to extract classes into reusable components. This way, you can apply multiple utility classes to an element at once using the custom class name.
.btn {
@apply py-2 px-4 bg-blue-500 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700;
}
In the above example, we've created a custom class called .btn
that applies several utility classes at once.
@apply
works best with utility classes and does not support pseudo-classes or variants. @apply
should be used sparingly, as Tailwind CSS encourages utility-first CSS. It can be beneficial for extracting complex styles that are used in multiple places.Let's take a look at some practical examples.
.card {
@apply p-6 mt-6 text-left border w-96 rounded-xl hover:text-blue-600 focus:text-blue-600;
}
In this example, we've created a .card
class that applies several utility classes.
.container {
@apply mx-auto px-4 sm:px-6 lg:px-8;
}
Here, we're using @apply
with responsive classes. The sm:
and lg:
prefixes apply styles at different screen sizes.
.custom-button {
@apply bg-theme-color text-white;
}
In this example, we're using @apply
to apply a custom theme color defined in the Tailwind CSS configuration file.
In this tutorial, we've learned:
@apply
directive in Tailwind CSSTo further develop your skills, you could explore more about customizing your Tailwind CSS configuration.
.hero
class that applies a set of utility classes for a full-width, center-aligned text over a background image.Solution:
css
.hero {
@apply w-full text-center bg-cover bg-center bg-no-repeat;
}
.card
class that changes padding and margins based on screen size.Solution:
css
.card {
@apply p-4 md:p-8 mt-4 md:mt-8;
}
.form-input
class that applies a set of utility classes including focus styles.Solution:
css
.form-input {
@apply px-4 py-2 border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-200 rounded-md;
}
Remember, the more you practice, the more you learn. Happy coding!