Overriding Variables
CSS variables can be overridden locally within a specific selector. This allows for contextual changes while maintaining the global definition for other elements. Overriding variables is useful for theming or applying styles dynamically.
Key Topics
Local Overrides
You can override global CSS variables within a specific selector. The overridden value applies to the element and its descendants.
<style>
:root {
--primary-color: #007BFF;
}
.global {
color: var(--primary-color);
}
.local {
--primary-color: #FF5733;
color: var(--primary-color);
}
</style>
<div class="global">Global Variable Applied</div>
<div class="local">Locally Overridden Variable</div>
Explanation: The --primary-color
is overridden in the .local
class, changing the text color for that selector and its descendants.
Nested Variables
When variables are nested within selectors, the most specific variable definition is applied.
<style>
:root {
--bg-color: #F0F0F0;
}
.section {
--bg-color: #D3D3D3;
background-color: var(--bg-color);
}
.highlight {
--bg-color: #FFD700;
background-color: var(--bg-color);
}
</style>
<div class="section">
Section Background
<div class="highlight">Highlighted Background</div>
</div>
Explanation: The --bg-color
variable is overridden in nested elements, allowing for contextual styling within the hierarchy.
Contextual Styling
Override variables dynamically based on the context, such as applying specific styles to a theme or a state.
<style>
:root {
--text-color: #000000;
}
.dark-theme {
--text-color: #FFFFFF;
background-color: #000000;
color: var(--text-color);
}
</style>
<div class="dark-theme">This is a dark-themed section</div>
Explanation: The --text-color
variable is overridden in the .dark-theme
class to match the dark mode design.
Key Takeaways
- Global and Local Variables: Use global variables in
:root
and override them locally for specific selectors. - Nesting: Variables can be nested and overridden based on hierarchy.
- Contextual Styling: Apply different values dynamically for themes or states.
- Maintainability: Overriding variables locally ensures flexibility while keeping global consistency.