Layer organization helps keep your styles neat and easy to find. It separates basic styles, reusable parts, and quick helpers.
0
0
Layer organization (base, components, utilities) in Tailwind
Introduction
When you want to set default styles for HTML elements like headings and paragraphs.
When you create reusable UI parts like buttons or cards.
When you need quick utility classes to adjust spacing or colors on the fly.
When working in a team to keep CSS organized and clear.
When your project grows and you want to avoid messy styles.
Syntax
Tailwind
@layer base {
/* base styles here */
}
@layer components {
/* component styles here */
}
@layer utilities {
/* utility styles here */
}@layer is a Tailwind directive to group styles.
Base is for default element styles, components for reusable parts, utilities for small helpers.
Examples
This sets a base style for all <h1> headings.
Tailwind
@layer base {
h1 {
font-size: 2rem;
font-weight: bold;
}
}This creates a reusable button style called
btn-primary.Tailwind
@layer components {
.btn-primary {
@apply bg-blue-500 text-white py-2 px-4 rounded;
}
}This adds a small utility class for text shadow.
Tailwind
@layer utilities {
.text-shadow {
text-shadow: 1px 1px 2px black;
}
}Sample Program
This example shows how base styles set default heading and paragraph looks. The component card adds a white box with shadow and padding. The utility text-shadow adds a subtle shadow to the heading text.
Tailwind
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Tailwind Layer Example</title> <script src="https://cdn.tailwindcss.com"></script> <style type="text/tailwindcss"> @layer base { h1 { @apply text-3xl font-bold text-gray-800; } p { @apply text-gray-600; } } @layer components { .card { @apply bg-white shadow-md rounded-lg p-6; } } @layer utilities { .text-shadow { text-shadow: 1px 1px 2px rgba(0,0,0,0.3); } } </style> </head> <body class="bg-gray-100 p-8"> <h1 class="text-shadow">Welcome to Tailwind Layers</h1> <p>This paragraph uses base styles for text color.</p> <div class="card mt-6"> <p>This is a card component with padding and shadow.</p> </div> </body> </html>
OutputSuccess
Important Notes
Use @layer to keep your CSS organized and avoid conflicts.
Base styles affect HTML elements globally, so be careful with overrides.
Components are great for reusable UI parts, utilities for quick tweaks.
Summary
Layer organization separates base, components, and utilities styles.
Base styles set default look for HTML elements.
Components hold reusable UI parts, utilities are small helper classes.