Performance: CSS custom properties vs SASS variables
This concept affects how CSS values are processed and updated in the browser, impacting rendering speed and dynamic style changes.
Jump into concepts and practice - no test required
:root {
--primary-color: #3498db;
}
.button {
background-color: var(--primary-color);
}
// Can change --primary-color dynamically with JavaScript without reload$primary-color: #3498db; .button { background-color: $primary-color; } // To change color dynamically, need to recompile CSS
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| SASS variables (static) | None at runtime | 0 | Minimal | [OK] Good for static styles |
| CSS custom properties (dynamic) | None unless JS changes styles | 0-1 per change | Low if used for paint-only properties | [!] OK with dynamic updates |
-- and are live in the browser, meaning they can be changed dynamically.$ and are replaced during the build process, so they don't exist in the browser.-- and work in the browser at runtime. -> Option D-- prefix and runtime [OK]$ and use a colon : to assign values.$primary-color: #3498db; uses correct syntax. --primary-color: #3498db; uses the CSS custom property prefix. primary-color: #3498db; omits the $ prefix. $primary-color == #3498db; uses double equals which is invalid.:root { --main-color: red; }
.box { color: var(--main-color); }
$main-color: blue;
.box2 { color: $main-color; }--main-color is set to red in :root. The class .box uses var(--main-color), so it will be red at runtime.$main-color is blue and used in .box2. This is replaced during compilation, so .box2 color will be blue in the final CSS.$color: green;
.text { color: var($color); }
var() function is a CSS function used only for CSS custom properties (those starting with --).$ and are used directly without var(). Using var($color) is invalid because var() expects a CSS custom property name.$primary-color: #0055ff;
:root { --primary-color: #0055ff; }
--) live in the browser and can be changed with JavaScript or media queries without recompiling CSS.--primary-color because it can change dynamically in the browser. -> Option A