Tailwind CSS Directives and Functions
In addition to utility classes, Tailwind also provides some special directives and functions that allow you to integrate more deeply with Tailwind's system in custom CSS.
@tailwind
This is the first directive you encounter, used to inject different parts of Tailwind into your main CSS file.
@tailwind base;
@tailwind components;
@tailwind utilities;@tailwind base: Injects Tailwind's base styles (a modern CSS reset called Preflight) and any base styles registered by plugins.@tailwind components: Injects Tailwind's component classes and any component classes registered by plugins.@tailwind utilities: Injects all of Tailwind's utility classes and any utility classes registered by plugins.
@layer
The @layer directive tells Tailwind which "layer" your custom styles belong to. This is very important for controlling CSS rule order and override relationships, especially when you want to add custom styles that can be overridden by utility classes (like hover: or focus:).
Tailwind has three main layers: base, components, and utilities.
Example: Custom Link Styles
If you want to define a base style for all <a> tags but still be able to override it with utility classes like text-red-500, you can do this:
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
a {
@apply text-blue-600 underline;
}
a:hover {
@apply text-blue-800;
}
}By placing custom styles in the base layer, you ensure they can be overridden by classes in the components and utilities layers.
@apply
The @apply directive allows you to extract a series of Tailwind utility classes into a custom CSS class. This is discussed in detail in the "Reusing Styles" chapter.
@layer components {
.card {
background-color: white;
border-radius: 0.5rem;
padding: 1.5rem;
box-shadow: theme('boxShadow.lg');
}
/* Equivalent using @apply */
.card-alternative {
@apply bg-white rounded-lg p-6 shadow-lg;
}
}Note: @apply doesn't handle CSS rule merging or overriding for you; it simply pastes the CSS corresponding to the utility classes. Therefore, overuse can lead to difficult-to-maintain code.
theme()
The theme() function allows you to access theme values defined in tailwind.config.js in your custom CSS. This is very useful when writing complex CSS that isn't suitable for @apply but you still want to reference values from your design system (like colors, spacing).
Example:
.content-area {
height: calc(100vh - theme('spacing.12'));
}
.main-title {
color: theme('colors.primary');
font-family: theme('fontFamily.sans');
}The theme() function uses dot notation to access nested theme values. It's a powerful tool for maintaining CSS flexibility while staying consistent with your design system.