Functions And Directives in TailwindCSS
In Tailwind CSS, "Functions and Directives" refer to the tools you use in your CSS (or Tailwind configuration) to control styling behavior and extend the framework. Here's a breakdown:
? Tailwind CSS Directives (Used in CSS files)
Tailwind uses PostCSS with special directives to inject utility classes:
1. @tailwind
Used to include Tailwind's layers (base, components, utilities):
@tailwind base;@tailwind components;@tailwind utilities;? Place this in your
input.cssorapp.css.
2. @apply
Used to apply Tailwind classes directly inside a CSS class:
.btn { @apply bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600;}3. @layer
Used to define custom styles in a specific layer (base, components, utilities):
@layer components { .card { @apply bg-white shadow-md rounded-lg p-4; }}4. @variants (Deprecated in Tailwind v3+)
Previously used to define responsive/hover/focus variants. Now replaced by the variant key in the config or just using modifiers like hover:.
?? Functions (in tailwind.config.js)
1. theme()
Access values from the Tailwind config:
module.exports = { theme: { extend: { colors: { primary: '#1D4ED8', }, }, },};Used in plugin functions:
plugin(({ addUtilities, theme }) => { const newUtilities = { '.content-auto': { contentVisibility: 'auto', }, }; addUtilities(newUtilities);});2. config()
Access global configuration options (less common than theme()).
Bonus: Safelisting classes
If you're using classes dynamically (e.g., in PHP or JS), Tailwind might purge them. Use safelist in tailwind.config.js:
safelist: [ 'text-red-500', 'bg-green-100', { pattern: /bg-(red|green|blue)-(100|500)/, }]Would you like to see how to create custom components using @apply or @layer?