Performance: Variable scope
Variable scope in CSS affects how and where custom properties (variables) are applied, impacting style recalculations and rendering performance.
Jump into concepts and practice - no test required
.card { --main-color: blue; --accent-color: orange; } .card .button { color: var(--main-color); }
:root { --main-color: blue; --accent-color: orange; } .button { color: var(--main-color); }| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Global CSS variables | Low DOM ops | High reflows on variable change | High paint cost if many elements use variables | [X] Bad |
| Scoped CSS variables | Low DOM ops | Low reflows limited to container | Lower paint cost due to limited scope | [OK] Good |
:root are global and accessible anywhere.:root selector -> Option B:root [OK]:root [OK]--main-color with value blue inside a class .header?--var-name: value;.var() on left side. .header { --main-color = blue; } uses equals sign which is invalid. .header { main-color: blue; } misses dashes.--name: value; [OK]--name: value; inside selectors [OK]<div class='box'> be?:root { --text-color: black; } .box { --text-color: red; color: var(--text-color); }--text-color is globally black in :root, but locally red inside .box..box, local variable overrides global, so color: var(--text-color) uses red.--bg-color is not applying inside .card?:root { --bg-color: yellow; } .card { background-color: var(--bg-color); } .card .content { --bg-color: green; }.card .content are local to that selector only.background-color is appliedbackground-color is set on .card, which uses the global variable from :root.--bg-color inside .content does not affect .card -> Option A--button-color to be blue globally but red only inside .alert buttons. Which CSS setup achieves this correctly?:root--button-color: blue in :root makes it global..alert button--button-color: red inside .alert button overrides global only there.button color propertycolor: var(--button-color) in button applies correct color depending on scope.:root, local override in selector [OK]:root, override locally in selector [OK]