Override Global Variable With Local Variable
Global variables can be used anywhere in the document, while local variables can only be used inside the selector where they are declared.
Sometimes you want a variable to change only in a specific part of the page.
To do this, you can re-declare the variable inside a more specific selector. When you use var() inside that selector, it will use the local value instead of the global one. The local variable overrides the global variable for that selector.
Example
Here, the .note selector re-declares --primary-bg-color as red. Inside .note, the local value is used instead of the global blue.
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Override Global Variable With Local Variable</title>
<style>
:root {
--primary-bg-color: #1e90ff;
--primary-color: #ffffff;
}
body {
background-color: var(--primary-bg-color);
}
.container {
color: var(--primary-bg-color);
background-color: var(--primary-color);
padding: 15px;
}
.container h2 {
border-bottom: 2px solid var(--primary-bg-color);
}
.container .note {
--primary-bg-color: red; /* local variable will override global */
border: 1px solid var(--primary-bg-color);
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<h2>Welcome</h2>
<p>This is a container with global variable colors.</p>
<div class="note">
<p>This note has a red border because the local --primary-bg-color overrides the global value.</p>
</div>
</div>
</body>
</html>
Add a New Local Variable
If a variable is only going to be used in one place, you can declare a brand new local variable instead of overriding the global one.
Example
Here, a new local variable --note-border-color is declared inside .note and used only for that element's border.
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add a New Local Variable</title>
<style>
:root {
--primary-bg-color: #1e90ff;
--primary-color: #ffffff;
}
body {
background-color: var(--primary-bg-color);
}
.container {
color: var(--primary-bg-color);
background-color: var(--primary-color);
padding: 15px;
}
.container h2 {
border-bottom: 2px solid var(--primary-bg-color);
}
.container .note {
--note-border-color: red; /* new local variable */
border: 1px solid var(--note-border-color);
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<h2>Welcome</h2>
<p>This is a container with global variable colors.</p>
<div class="note">
<p>This note has a red border using a new local variable --note-border-color.</p>
</div>
</div>
</body>
</html>