• Attempts to get the value associated with CSS variable name from the target.

    If no target is specified, uses documentElement (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.

    Type Parameters

    • V extends CssVarValue = string

      Type of value to return.

    Parameters

    • name: `--${string}`

      Name of the variable to get value for.

    • Optionaltarget: null | Target = document.documentElement

      Optional Element, EventTarget, or CSS selector.

    Returns V | undefined

    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"