Type of value to return.
Name of the variable to get value for.
Optional
target: null | Target = document.documentElementOptional Element, EventTarget, or CSS selector.
Value associated with the name
or undefined
if it doesn't exist.
The function throws if the target
doesn't exist, rather than just falling
back to the :root
element. If you specify a target
, you probably want to
get the CSS variable on that target
.
InvalidCssVarError
if the specified name
is invalid.
elements!InvalidElementError
if the specified target
wasn't found.
HTML
<style>
:root {
--color-fg: green;
}
</style>
<button id="example" style="--color-bg: blue; --gap: 24;">
Example
</button>
Get from Element
const element = findElement("#example")!;
getCssVar("--color-bg", element);
// "blue"
getCssVar("--gap", element);
// 24
Get from :root
getCssVar("--color-fg");
// "green"
Attempts to get the value associated with CSS variable
name
from thetarget
.If no
target
is specified, usesdocumentElement
(i.e.:root
).If found, the value is coerced to a numeric value if number-like, or a boolean if
"true"
or"false"
. All CSS variables are technically strings, but it's nice to get/set the actual type without worrying about string conversion first.