Performance: Why reusable patterns matter
Reusable patterns reduce CSS duplication and DOM complexity, improving page load speed and rendering efficiency.
<style>
@layer components {
.btn-blue {
@apply bg-blue-500 text-white p-4 rounded;
}
}
</style>
<div class="btn-blue">Button 1</div>
<div class="btn-blue">Button 2</div>
<div class="btn-blue">Button 3</div><div class="bg-blue-500 text-white p-4 rounded">Button 1</div> <div class="bg-blue-500 text-white p-4 rounded">Button 2</div> <div class="bg-blue-500 text-white p-4 rounded">Button 3</div>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Repeated utility classes inline | Multiple style recalculations | Multiple reflows if layout changes | Higher paint cost due to complexity | [X] Bad |
| Reusable Tailwind component class | Single style calculation reused | Minimal reflows | Lower paint cost | [OK] Good |
@apply directive lets you combine utility classes into one reusable class.@import loads CSS files, @media handles responsiveness, and @font-face loads fonts, none create reusable classes.@apply directive -> Option A@apply = reusable styles [OK]@apply combines utilities into reusable classes [OK]@apply with @import@media creates reusable classes<button class="btn-primary p-4">Click Me</button>
/* CSS */
.btn-primary {
@apply bg-blue-600 text-white rounded-lg;
}@apply usage.btn-primary class applies bg-blue-600, text-white, and rounded-lg styles.p-4 class adding padding around the content.@apply adds Tailwind utilities to custom classes [OK]p-4@apply changes text color to blue@apply:.btn {
@apply bg-green-500 text-white p-3 rounded;
}
.btn {
@apply bg-red-500;
}@apply on same class@apply twice on .btn means the second overrides the first styles.@apply bg-red-500 replaces the green background, causing inconsistency.@apply overrides the first, causing inconsistent styles. -> Option B@apply on same class = override [OK]@apply for base styles and adding hover utilities in HTML keeps code clean and flexible.@apply with base styles and add hover utilities in HTML. -> Option DPass the test and this pattern moves unknown