1

Now that CSS supports not only custom properties but also environment variables I would like to know how they can be changed programmatically using javascript.

The following example will render a text in purple color. Is it possible to change it to another color e.g. after 5 seconds using a setTimeout?

div {
  color: env(PRIMARY, purple)
}
<div>Hello world</div>
jantimon
  • 36,840
  • 23
  • 122
  • 185
  • Isn't the only reason it's turning the text `purple` because there is no `env` variable for `PRIMARY`, so it's relying on the fallback? From my understanding, custom `env` variables set by stylesheet authors isn't supported yet or at least there's no spec set on how it will be implemented. And, I believe this might not work as the purpose of `env` variables is to make them a static value. – disinfor Jun 07 '19 at 18:52
  • Actually I would like to have a javascript controlled media query - https://stackoverflow.com/a/47212942/159319 explains that this will be possible with `env` and I was hoping that now that it is part of the browser it might already work – jantimon Jun 07 '19 at 20:40
  • Ahh. Your question doesn't mention `media` queries. You might want to update the question to include that information - for future visitors. And still, browsers support a very limited set of `env` variables - the ones hard coded into the browser - as custom ones do not appear to be available yet. Once the spec is figured out for custom `env` vars, I think this will allow for some interesting functionality! – disinfor Jun 09 '19 at 15:23

1 Answers1

0

Setting the variable in :root and then accessing that variable in env allows you to modify it via javascript.

var obj = document.getElementById("test");
setTimeout(function(){
    obj.style.setProperty("--primary","black");
},2000);
:root{
   color:env(--primary,red);
}

#test {
  color: var(--primary)
}
<div id="test">Hello world</div>
imvain2
  • 15,480
  • 1
  • 16
  • 21
  • 2
    Thanks for your answer! Unfortunately it is not what I meant. You are using `var` but I asked how you would do that for `env` – jantimon Jun 07 '19 at 20:37
  • @jantimon, I updated my answer to be a combo of `var` and `env` and it still works. – imvain2 Jun 07 '19 at 20:50
  • 1
    But your code changes the `var` not the `env` value. `var` values must not be used inside media queries – jantimon Jun 08 '19 at 09:50
  • @jantimon did you find a way to achieve it ? I created a ticket on MDN: https://discourse.mozilla.org/t/question-is-there-a-way-to-override-css-native-env-variable-like-safe-area-inset-top/79675 – Aarbel Oct 18 '21 at 08:32