216

Is there a way to access a css variable from javascript? Here my css variable declaration.

:root {
  --color-font-general: #336699;
}
5
  • 2
    I am really curious as to why you don't want to re-declare that variable in javascript which is more efficient Commented Jan 18, 2017 at 17:29
  • 20
    @Dummy Then there would be two places in which the value needed to be maintained, making the code more fragile (i.e. not a DRY approach). Commented Nov 8, 2018 at 10:27
  • 1
    In my case, I don't know which CSS file it's using. The user decides the file, and each file has different values for this variable. Commented Jan 1, 2019 at 1:10
  • 4
    Also, if you have CSS variables that have different values depending on which active @media query defines them, you save yourself even more work and duplicate code. Commented Jan 8, 2019 at 5:00
  • @ClausWahlers which is why I'm here lolol, had to refresh myself on this, been a while Commented Oct 7, 2024 at 18:21

2 Answers 2

381

Just the standard way:

  1. Get the computed styles with getComputedStyle
  2. Use getPropertyValue to get the value of the desired property
window.getComputedStyle(element).getPropertyValue('--color-font-general');

Example:

var style = window.getComputedStyle(document.body)
console.log( style.getPropertyValue('--bar') ) // #336699
console.log( style.getPropertyValue('--baz') ) // calc(2px*2)
:root { --foo:#336699; --bar:var(--foo); --baz:calc(2px*2); }

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

8 Comments

@webkitfanz you do realize that css variables are not supported in IE, right?
Is there a way to do this without causing a reflow as getComputedStyle will do this?
Note that the value returned has the leading space, so you would get " #336699" instead of "#336699". This matters if you are trying to check the value (it may not match because of that leading space, so consider trimming it before checking).
@EricMutta I just experienced this. So annoying. Why would they return with a leading space in the string?
@Lilboat It doesn't matter; window is the global object.
|
88

Use this:

window.getComputedStyle(document.documentElement).getPropertyValue('--color-font-general');

And you can change it like this:

document.documentElement.style.setProperty('--color-font-general', '#000');

source

4 Comments

It actually would be document.documentElement.style.setProperty('--color-font-general', '#000'); if you wanted to change it.
whoops fixed. thanks!
You can also get it like that: element.style.getPropertyValue()
@Rudie element.style.getPropertyValue() will only work if the variable has been set on the inline style of the element (not through a CSS rule)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.