0
0
Tailwindmarkup~8 mins

Class-based dark mode strategy in Tailwind - Performance & Optimization

Choose your learning style9 modes available
Performance: Class-based dark mode strategy
MEDIUM IMPACT
This affects page load speed and rendering performance by controlling when and how dark mode styles are applied.
Implementing dark mode toggle with Tailwind CSS
Tailwind
/* Using class-based dark mode */
@tailwind base;
@tailwind components;
@tailwind utilities;

/* Tailwind config: darkMode: 'class' */

<body class="dark">
  <div class="bg-white dark:bg-gray-900 text-black dark:text-white">
    Hello World
  </div>
</body>
Dark mode styles apply only when the 'dark' class is present, avoiding unnecessary style recalculations on load.
📈 Performance GainSingle style calculation on load, no forced reflow from media query changes
Implementing dark mode toggle with Tailwind CSS
Tailwind
/* Using media query dark mode */
@tailwind base;
@tailwind components;
@tailwind utilities;

/* Tailwind config: darkMode: 'media' */

<body>
  <div class="bg-white dark:bg-gray-900 text-black dark:text-white">
    Hello World
  </div>
</body>
Dark mode styles are applied based on user system preferences, causing a flash of incorrect theme if user toggles manually later.
📉 Performance CostTriggers style recalculation on initial load and possible reflow if user changes system theme
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Media query dark modeNo extra DOM nodesTriggers reflow on system theme changeMedium paint cost due to style recalculation[X] Bad
Class-based dark modeAdds one class to <body>Single reflow on class toggleLower paint cost, stable layout[OK] Good
Rendering Pipeline
The browser applies styles based on the presence of the 'dark' class, avoiding media query recalculations and reducing layout shifts.
Style Calculation
Layout
Paint
⚠️ BottleneckStyle Calculation due to media query evaluation in bad pattern
Core Web Vital Affected
LCP
This affects page load speed and rendering performance by controlling when and how dark mode styles are applied.
Optimization Tips
1Use class-based dark mode to control when dark styles apply.
2Avoid media query dark mode to reduce style recalculations on load.
3Toggle the 'dark' class on a high-level element like <body> for best performance.
Performance Quiz - 3 Questions
Test your performance knowledge
Which dark mode strategy reduces style recalculations on page load?
AClass-based dark mode using a 'dark' class
BMedia query dark mode based on system preferences
CInline styles toggled by JavaScript
DUsing !important in CSS for dark mode styles
DevTools: Performance
How to check: Record a performance profile while toggling dark mode class on <body>. Observe style recalculations and layout shifts.
What to look for: Look for fewer style recalculations and layout shifts in class-based approach compared to media query approach.