css-var-resolver
v1.0.0
Published
Read CSS custom properties (variables) from JavaScript with optional fallback values.
Maintainers
Readme
css-var-resolver
Read CSS custom properties (variables) from JavaScript with optional fallback values.
css-var-resolver is a tiny, zero-dependency utility to read CSS variables from JavaScript at runtime. It returns the computed value of a CSS custom property and allows specifying a fallback value if the variable is not defined. Works in vanilla JS, React, or any frontend project.
Install
npm install css-var-resolver
# or
pnpm add css-var-resolver
# or
yarn add css-var-resolverUsage
ESM
import { cssVar } from 'css-var-resolver';
const primaryColor = cssVar('--primary-color', '#000');
console.log(primaryColor); // computed value or '#000' if undefinedCommonJS
const { cssVar } = require('css-var-resolver');
const gap = cssVar('spacing-unit', '8px'); // name without `--` also worksWith a specific element
// Read from a specific element instead of :root
actionBar.style.setProperty('--action-bg', 'rebeccapurple');
const bg = cssVar('--action-bg', '#444', actionBar);API
function cssVar<T = string | undefined>(
name: string, // '--primary-color' or 'primary-color'
fallback?: T, // value if missing or when no DOM (SSR)
element?: Element // defaults to document.documentElement
): string | T | undefined- Accepts names with or without the
--prefix. - Safe in SSR and non-DOM environments: returns
fallback. - Trims the returned value.
Why?
- Dynamic theming: read tokens defined via CSS variables
- Responsive styling: derive values computed by the browser
- No build step required: works directly in the browser
- Zero dependencies, tree-shakeable
Edge cases
- If the variable is not defined (or resolves to empty), the
fallbackis returned. - In server-side rendering or non-DOM environments,
fallbackis returned. - If you omit
fallback, the function may returnundefined.
License
MIT © 2025 venisha-kalola
