You’re likely here because you’ve faced long, unmanageable Tailwind classes in your codebase.
Fortunately, there is a way to resolve this using Tailwind’s ‘@layer components’. While this is not a complete solution, it enhances the maintainability of your codebase.
The ‘@layer components’ feature lets you create and reuse custom components with Tailwind classes throughout your project.
Before this can work, make sure to include the ‘@tailwind components;’ directive in your CSS file.
@tailwind components;
After adding the directive, you can now use the ‘@layer components’ feature as demonstrated below.
@layer components {
.page-header {
@apply text-2xl font-bold text-gray-900
sm:text-3xl sm:font-extrabold sm:text-blue-800
md:text-4xl md:font-semibold md:text-green-800
lg:text-5xl lg:font-medium lg:text-red-800;
}
.page-paragraph {
@apply text-base text-gray-600
sm:text-lg sm:text-blue-700
md:text-xl md:text-green-700
lg:text-2xl lg:text-red-700;
}
}
Once the components have been defined, you can substitute their values for the component names in your HTML file, as shown in the example below.
<div>
<h1
class="page-header">
Page Header
</h1>
<p
class="page-paragraph">
Page Paragraph
</p>
</div>
With the ‘@layer components’ feature, you can easily create various reusable components for use throughout your codebase. Changing the styles for a component only needs to be done in one place, and the styles will reflect throughout your codebase.