Variable scope in CSS decides where a variable can be used. It helps keep styles organized and avoid mistakes.
0
0
Variable scope in CSS
Introduction
When you want a color variable to be used only inside one section of a webpage.
When you need a font size variable that applies to the whole page.
When you want to change a variable for a specific component without affecting others.
When you want to keep your CSS clean by limiting variable use to certain parts.
Syntax
CSS
:root { --main-color: blue; }
section { --section-color: green; }Variables defined in :root are global and can be used anywhere.
Variables defined inside a selector like section are local to that selector and its children.
Examples
This sets a global background color variable used by the whole page.
CSS
:root {
--main-bg: lightgray;
}
body {
background-color: var(--main-bg);
}The
--text-color variable is local to article. Paragraphs outside article use black as fallback.CSS
article {
--text-color: darkred;
color: var(--text-color);
}
p {
color: var(--text-color, black);
}The header uses its local font size variable, while footer uses the global one.
CSS
:root {
--font-size: 1rem;
}
header {
--font-size: 1.5rem;
font-size: var(--font-size);
}
footer {
font-size: var(--font-size);
}Sample Program
The global variable --main-color is blue. Inside the section, it is overridden to green. Paragraphs inside the section show green text, others show blue.
CSS
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>CSS Variable Scope Example</title> <style> :root { --main-color: blue; } section { --main-color: green; color: var(--main-color); padding: 1rem; border: 2px solid var(--main-color); margin-bottom: 1rem; } p { color: var(--main-color); } </style> </head> <body> <p>This paragraph uses the global main color.</p> <section> <p>This paragraph uses the section's main color.</p> </section> <p>This paragraph again uses the global main color.</p> </body> </html>
OutputSuccess
Important Notes
Use :root to define variables that should be available everywhere.
Variables inside selectors only affect that selector and its children.
If a variable is not found locally, CSS looks up to the parent scopes until it finds it or uses fallback.
Summary
CSS variables have scope: global (usually :root) or local (inside selectors).
Local variables override global ones inside their scope.
Understanding scope helps keep styles organized and predictable.