Performance: Theme implementation basics
This affects page load speed and rendering performance by how CSS variables and theme styles are applied and recalculated.
Jump into concepts and practice - no test required
:root { --bg-color: white; --text-color: black; }
body { background-color: var(--bg-color); color: var(--text-color); }
body.dark-theme { --bg-color: black; --text-color: white; }body { background-color: white; color: black; } /* for light theme */
body.dark-theme { background-color: black; color: white; }| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple CSS class toggles for theme | Minimal DOM changes | Multiple reflows triggered | High paint cost due to many property changes | [X] Bad |
| CSS custom properties for theme colors | Minimal DOM changes | Single reflow triggered | Lower paint cost with efficient repaint | [OK] Good |
:root selector targets the top-level element for global variables.body is less specific than :root.<div class='dark'> be?:root { --text-color: black; } .dark { --text-color: white; } p { color: var(--text-color); }<div class='dark'><p>Hello</p></div>
:root, --text-color is black by default..dark class changes --text-color to white.p inside .dark uses white color from overridden variable.:root { --bg-color: white; } .dark-theme { --bg-color: black; } body { background-color: var(bg-color); }var(--variable-name), missing dashes cause errors.Choose the best approach:
:root sets defaults; overriding in a class like .dark changes theme colors..dark on body switches themes without reloading or inline styles.