Skip to content
CSS·Intermediate·Coding·1 min read

How can JavaScript read or set a custom property at runtime?

Short interview answer

getComputedStyle(el).getPropertyValue('--name') reads the resolved value, and el.style.setProperty('--name', value) sets it inline on that element, which then cascades to its descendants exactly like a CSS-authored override would — this is how a user-adjustable accent color or a JS-driven theme switch is typically wired up without a CSS-in-JS runtime.

Example

CSS
document.documentElement.style.setProperty('--brand', userColor);getComputedStyle(el).getPropertyValue('--gap').trim(); // "8px"

Key takeaway

Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.

← Back to Custom properties and theming

Related questions