0

Is it possible to override the local CSS variable with a global variable? As we know vice-versa is always possible. Can someone help if there is anything like !important to override the local variable.

Taking the below example, want red to have more precedence than blue.

 :root{
    --primarycolor: red !important; /*Like this*/
  }
  body {
    color: var(--primarycolor);
    border:2px solid var(--primarycolor);
    padding:5px;
  }
  div{
    --primarycolor: blue; /*Want to override this*/
    color: var(--primarycolor);
    border:2px solid var(--primarycolor);
    padding:5px;
  }
Check all border color - I am in body
<div>I am in div</div>
Jyothi Babu Araja
  • 10,076
  • 3
  • 31
  • 38
  • 1
    As far as I know, there is no such feature in CSS. Instead what you can do is to use fallback values `var(--primary-color, blue);`. See https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties#Custom_property_fallback_values – snwfdhmp Nov 18 '20 at 12:19
  • don't define the local variable then – Temani Afif Nov 18 '20 at 12:20
  • @TemaniAfif Actually I update the global variable with JS dynamically. Thank you I didn't mention that. – Jyothi Babu Araja Nov 18 '20 at 12:22

1 Answers1

2

Instead of :root use *. It won't be a global variable but still declared as a global one that will apply to all the element (instead of being inherited by all the element)

* {
  --primarycolor: red !important; /*Like this*/
}

body {
  color: var(--primarycolor);
  border: 2px solid var(--primarycolor);
  padding: 5px;
}

div {
  --primarycolor: blue; /*Want to override this*/
  color: var(--primarycolor);
  border: 2px solid var(--primarycolor);
  padding: 5px;
}
Check all border color - I am in body
<div>I am in div</div>

And without important the local one will apply since it's more specific:

* {
  --primarycolor: red;
}

body {
  color: var(--primarycolor);
  border: 2px solid var(--primarycolor);
  padding: 5px;
}

div {
  --primarycolor: blue; 
  color: var(--primarycolor);
  border: 2px solid var(--primarycolor);
  padding: 5px;
}
Check all border color - I am in body
<div>I am in div</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415