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>

3
  • 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 developer.mozilla.org/en-US/docs/Web/CSS/… Commented Nov 18, 2020 at 12:19
  • don't define the local variable then Commented Nov 18, 2020 at 12:20
  • @TemaniAfif Actually I update the global variable with JS dynamically. Thank you I didn't mention that. Commented Nov 18, 2020 at 12:22

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

@JyothiBabuAraja check this: stackoverflow.com/a/14791415/8620333

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.