Search code examples
cssscopeweb-frontendcss-variables

Accessing global variable in css


:root { 
  --color: blue; 
}

div { 
  --color: green;
    color: var(--color) 

}

#alert { 
  --color: red; 
    color: var(--color) 
}
<p>What's my color?</p>

<div>and me?</div>

<div id='alert'>  
  What's my color too?  
  <p>color?</p>
</div>

In the above code, how can I access the global value of --color in div with id='alert'? Or in other words is there any way in CSS to access the global variable like the :: (scope resolution operator) in c++??


Solution

  • You Can't do that with CSS.

    If You'll repeat the declaration of the same variable, it'll use the locally declared variable.

    See this-

    :root { --color: blue; }
    div { --color: green; }
    #alert { --color: red; }
    * { color: var(--color); }
    <p>I inherited blue from the root element!</p>
    <div>I got green set directly on me!</div>
    <div id='alert'>
      While I got red set directly on me!
      <p>I’m red too, because of inheritance!</p>
    </div>

    Source: Example 5 CSSWG