How to use @apply with custom CSS classes in TailwindCSS? In TailwindCSS, the @apply directive enables you to apply Tailwind's utility classes to your custom CSS. To use @apply with custom CSS classes, you must create a custom class in your CSS file and use the @apply directive to add the required Tailwind utility classes.
Below is an example demonstrating how to apply multiple utility classes to a custom CSS class in a TailwindCSS project using the @apply directive:
css/* Import Tailwind's base styles */ @import 'tailwindcss/base'; @import 'tailwindcss/components'; @import 'tailwindcss/utilities'; /* Create a custom CSS class */ .btn-custom { @apply bg-blue-500 text-white py-2 px-4 rounded; } /* Alternatively, you can use it in responsive design */ .btn-responsive { @apply px-4 py-2; @apply md:px-6 md:py-3; }
In this example, the .btn-custom class will have a blue background, white text, vertical padding py-2, horizontal padding px-4, and rounded corners. The .btn-responsive class has different padding settings for mobile and desktop devices, with the md: prefix indicating styles that apply at the medium breakpoint (i.e., desktop devices).
When using @apply, the following rules should be followed:
@applycannot be used with complex selectors, such as nested selectors in pseudo-classes or media queries.@applycan only be used at the top level of CSS rules, not within nested rules.- Other CSS declarations cannot be included in the same rule as
@apply, unless they are Tailwind's custom utility classes or components.
Ensure that you have installed TailwindCSS and correctly configured its build process in your actual project, as TailwindCSS requires its build tools to process the @apply directive.