Performance: Why CSS variables are used
CSS variables affect how styles are applied and updated, impacting rendering speed and layout stability.
Jump into concepts and practice - no test required
:root { --main-color: #3498db; } .btn { color: var(--main-color); } .header { background-color: var(--main-color); }:root { --main-color: #3498db; } .btn { color: #3498db; } .header { background-color: #3498db; }| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Repeated hardcoded values | Minimal | Multiple on updates | Moderate | [X] Bad |
| Using CSS variables | Minimal | Single on variable change | Lower | [OK] Good |
--main-color with the value #3498db?:root.:root { --main-color: #3498db; } which is correct. Others use wrong selectors or assignment operators.<div> in this CSS?:root { --bg-color: lightgreen; } div { background-color: var(--bg-color); }--bg-color is set to lightgreen in :root, making it global.div uses background-color: var(--bg-color); which applies the variable's value.:root { --text-color: blue } p { color: var(text-color); }--text-color is declared correctly except missing semicolon, but CSS allows last property without semicolon.var(), the variable name must include the double dashes --. Here it is missing.:root allows changing one value to update all uses.--main-color in :root and use var(--main-color) everywhere uses variables globally, making updates simple. Options B, C, and D are less efficient or more complex.