How to Override CSS Variable: Simple Guide with Examples
To override a CSS variable, define the same
--variable-name in a more specific selector or later in the stylesheet. CSS variables follow normal cascading rules, so the closest or last declared variable value will be used.Syntax
CSS variables are declared with --variable-name inside a selector and accessed using var(--variable-name). To override, redeclare the variable in a selector with higher specificity or later in the CSS.
--variable-name: value;— declares the variable.var(--variable-name)— uses the variable.- Override by redeclaring
--variable-namein a more specific or later rule.
css
:root {
--main-color: blue;
}
/* Override in a specific class */
.button {
--main-color: red;
}
.element {
color: var(--main-color);
}Example
This example shows a global CSS variable --main-color set to blue. Inside the .button class, the variable is overridden to red. The text color changes accordingly.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> :root { --main-color: blue; } body { font-family: Arial, sans-serif; } .text { color: var(--main-color); font-size: 1.5rem; margin: 1rem; } .button { --main-color: red; } .button .text { font-weight: bold; } </style> <title>Override CSS Variable Example</title> </head> <body> <div class="text">This text is blue (default variable).</div> <div class="button"> <div class="text">This text is red (overridden variable).</div> </div> </body> </html>
Output
Two lines of text: The first line is blue, the second line inside a red container is red and bold.
Common Pitfalls
Common mistakes when overriding CSS variables include:
- Declaring the override in a selector with lower specificity or before the original declaration, so it has no effect.
- Forgetting that variables are inherited, so overriding inside a container affects only its children.
- Using
var(--variable-name)without a fallback value when the variable might be undefined.
css
/* Wrong: override declared before original, no effect */ :root { --main-color: blue; } .button { --main-color: red; } /* Right: override declared after original */ :root { --main-color: blue; } .button { --main-color: red; }
Quick Reference
- Declare variables inside
:rootfor global scope. - Override by redeclaring in a more specific selector or later in CSS.
- Use
var(--variable-name, fallback)to provide a fallback value. - Remember variables cascade and inherit like normal CSS properties.
Key Takeaways
Override CSS variables by redeclaring them in a more specific or later CSS rule.
Variables declared in :root apply globally unless overridden in child selectors.
Use var(--name, fallback) to avoid errors if a variable is missing.
CSS variables inherit and cascade like normal CSS properties.
Order and specificity determine which variable value is used.