In this section we will see how to use @apply directive in tailwind css. Tailwind @apply directive using for create short and reusable class. If you are using framework like laravel, react or vue then do not use @apply directive. this framework have there own reusable style. but you can use small components like button, color and style classes.
Before start you need to first install & setup tailwind css.
How to install & setup Tailwind CSS v3
Example 1
Create button using @apply directive
src/input.css or main.css or tailwind.css
@tailwind base;
@tailwind components;
.btn {
@apply px-4 py-2 font-bold rounded;
}
.btn-blue {
@apply px-4 py-2 font-bold text-white bg-blue-500 rounded hover:bg-blue-700;
}
@tailwind utilities;
use .btn and .btn-blue.
<button class="btn btn-blue">Button</button>
If you like bootstrap class name style then you can use @apply to create button like this.
@tailwind base;
@tailwind components;
.btn {
@apply px-4 py-2 font-bold rounded;
}
.btn-blue {
@apply px-4 py-2 font-bold text-white bg-blue-500 rounded hover:bg-blue-700;
}
.btn-success {
@apply px-4 py-2 font-bold text-white bg-green-500 rounded hover:bg-green-700;
}
.btn-danger {
@apply px-4 py-2 font-bold text-white bg-red-500 rounded hover:bg-red-700;
}
@tailwind utilities;
Bootstrap like button style using @apply.
<button class="btn btn-blue">Button</button>
<button class="btn btn-success">Success Button</button>
<button class="btn btn-danger">Danger Button</button>
Example 2
You can also create base typography value.
src/input.css or main.css or tailwind.css
@tailwind base;
@layer base {
h1 {
@apply text-5xl;
}
h2 {
@apply text-4xl;
}
h3 {
@apply text-3xl;
}
h4 {
@apply text-2xl;
}
h5 {
@apply text-xl;
}
h6 {
@apply text-lg;
}
}
@tailwind components;
@tailwind utilities;
Set default value h1,h2...h6 using tailwind @apply directive.
<div>
<h1>h1 set deafult value using @apply directive</h1>
<h2>h2 set deafult value using @apply directive</h2>
<h3>h3 set deafult value using @apply directive</h3>
<h4>h4 set deafult value using @apply directive</h4>
<h5>h5 set deafult value using @apply directive</h5>
<h6>h4 set deafult value using @apply directive</h6>
</div>