0
0
CSSmarkup~10 mins

Variable scope in CSS - Browser Rendering Trace

Choose your learning style9 modes available
Render Flow - Variable scope
Parse CSS file
Identify :root variables
Identify variables in selectors
Build cascade and inheritance
Apply variables based on scope
Render styles with resolved values
The browser reads CSS variables from global (:root) and local selectors, then applies them based on where they are defined and used, resolving the final values during rendering.
Render Steps - 3 Steps
Code Added::root { --main-color: blue; }
Before
[ ]

No color variable defined, text uses default color (black).
After
[ ]

--main-color set globally to blue, but no element uses it yet.
The global variable --main-color is defined as blue, available to all elements unless overridden.
🔧 Browser Action:Stores variable in global scope for later use.
Code Sample
A paragraph inside a container uses a CSS variable for color; the variable is defined globally as blue but locally as red inside the container, so the paragraph text appears red.
CSS
<div class="container">
  <p class="text">Hello World</p>
</div>
CSS
:root {
  --main-color: blue;
}
.container {
  --main-color: red;
}
.text {
  color: var(--main-color);
}
Render Quiz - 3 Questions
Test your understanding
After applying step 2, what is the value of --main-color inside the .container element?
Ablack
Bblue
Cred
Dundefined
Common Confusions - 2 Topics
Why does my element not use the global variable value?
If a parent element defines the same variable locally, the child uses that local value instead of the global one. Variables follow normal CSS cascade and scope rules (see render_steps 2 and 3).
💡 Local variable definitions override global ones inside their subtree.
Can variables defined inside one selector be used outside it?
No. Variables defined inside a selector only apply to that selector and its children. Outside elements do not see those local variables (see render_steps 2).
💡 Variables have block scope like CSS properties.
Property Reference
PropertyScopeVisual EffectCommon Use
--variable-nameGlobal (:root)Available everywhere unless overriddenDefine default theme colors
--variable-nameLocal (inside selector)Overrides global variable within that selector's subtreeCustomize styles for specific sections
var(--variable-name)UsageUses the variable value from nearest scopeApply colors, sizes, or other CSS values dynamically
Concept Snapshot
CSS variables can be defined globally (:root) or locally inside selectors. Local variables override global ones inside their scope. Use var(--name) to access the nearest scoped variable. Variables follow normal CSS cascade and inheritance rules. This allows flexible theming and style customization.