Performance: Declaring variables
Declaring CSS variables affects how styles are computed and reused, impacting style calculation and paint performance.
Jump into concepts and practice - no test required
:root { --primary-color: #3498db; }
.button { color: var(--primary-color); background-color: var(--primary-color); border-color: var(--primary-color); }:root { }
.button { color: #3498db; background-color: #3498db; border-color: #3498db; }| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Repeating literal values | Minimal | Minimal | Higher due to repeated style calculations | [X] Bad |
| Using CSS variables | Minimal | Minimal | Lower due to reuse of computed values | [OK] Good |
:root?:root in CSS:root selector targets the highest-level element in the document, usually the <html> element.:root makes them global, so they can be used anywhere in the CSS.:root declaration [OK]:root for global access [OK]:root are local--main-color with the value #3498db inside :root?-- and are declared with a colon : inside a selector block.--main-color: #3498db;. Others use invalid symbols or keywords.--name: value; [OK]--name: value; inside :root [OK]-- prefixvar() in declaration:root {
--text-color: #ff0000;
}
p {
color: var(--text-color);
}--text-color is set to #ff0000, which is red.color: var(--text-color);, so it will use the red color.var(--name) usage [OK]var() to apply variables:root {
--bg-color #ffffff;
}
body {
background-color: var(--bg-color);
}--bg-color #ffffff; is missing a colon : between the variable name and value.background-color: var(--bg-color); is correct, so the error is only in declaration.--primary-color and --secondary-color. You want --secondary-color to be 50% transparent version of --primary-color. Which CSS variable declaration correctly achieves this?var(--primary-color) inside rgba() expecting it to split into RGB components.rgba(var(--primary-color), 0.5) but --primary-color is a hex string, so this won't work.--primary-color as RGB components but CSS variables cannot hold multiple values like that easily.#0000ff80 which is blue with 50% opacity, correctly representing a transparent version.var() with a second parameter that is not opacity.