fn

useCssVar

v0.0.14testeddemo

Read and write a CSS custom property on an element as a reactive ref. Defaults to document.documentElement. Set observe to react to external changes via a MutationObserver.

Examples

ts
const color = useCssVar('--color', el);
color.value = 'red';
ts
const theme = useCssVar('--theme', null, { initialValue: 'light', observe: true });

Demo

Loading demo…

Signature

ts
export function useCssVar(
  prop: MaybeRefOrGetter<string | null | undefined>,
  target?: MaybeComputedElementRef,
  options: UseCssVarOptions ={ ... }

Parameters

ParameterTypeDescription
propMaybeRefOrGetter<string | null | undefined>The CSS variable name (e.g. --color)
target?MaybeComputedElementRefElement to read/write the variable on (defaults to documentElement)
options?UseCssVarOptionsinitialValue, observe, and a configurable window

Returns

UseCssVarReturnA writable ref; reading returns the current value, writing updates the property