Tailwind's utility-first approach means you often combine many classes. For frequently repeated combinations, `@apply` (in a CSS file with a build process) can help create custom classes.
Imagine these buttons need to look the same across your site:
The buttons above repeat these classes:
bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded
.
If you were using Tailwind with a CSS file and a build step (e.g., PostCSS), you could define a custom class like
.btn-primary
using
@apply
:
/* In your CSS file (e.g., input.css) */
.btn-primary {
@apply bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded;
}
Then, in your HTML, you'd simply use:
<button class="btn-primary">Primary Button</button>
.
Note:
This HTML file uses the Tailwind CDN, so
@apply
directives in a
<style>
tag here won't be processed. This example is purely illustrative of the concept.
While
@apply
seems convenient, overusing it can lead to issues. The next example will explore this "Gotcha" in more detail.