How can I override a CSS variable defined in a parent element?
Asked on Oct 14, 2025
Answer
To override a CSS variable defined in a parent element, you can redefine the variable in a child element's CSS rule. This allows the child element to use the new value while the parent and other elements remain unaffected.
<!-- BEGIN COPY / PASTE -->
<style>
.parent {
--main-color: blue;
}
.child {
--main-color: red; /* Override the variable */
color: var(--main-color);
}
</style>
<div class="parent">
<p>This text is blue.</p>
<div class="child">
<p>This text is red.</p>
</div>
</div>
<!-- END COPY / PASTE -->Additional Comment:
- CSS variables (custom properties) are defined using the syntax: --variable-name: value;
- To use a CSS variable, reference it with var(--variable-name);
- Variables are inherited, so redefining them in a child element changes their value only within that scope.
- Ensure the variable is defined before it's used in the CSS rule to avoid fallback issues.
Recommended Links: