How JavaScript Interacts with CSS Custom Properties

JavaScript communicates with CSS custom properties (commonly known as CSS variables) through the CSS Object Model (CSSOM), allowing developers to dynamically read, modify, and delete styles at runtime. By leveraging interfaces such as getComputedStyle, CSSStyleDeclaration, and the modern CSS Typed Object Model, scripts can alter theme configurations, respond to user interactions, and synchronize styling logic directly with the document tree or global :root scope.

Reading CSS Custom Properties

To read the active value of a CSS custom property on any element, you must use window.getComputedStyle(). This method resolves all inheritance, cascading rules, and stylesheets, returning a live CSSStyleDeclaration object.

// Target the root element (:root) or any specific DOM element
const rootElement = document.documentElement;

// Retrieve the computed styles
const computedStyles = window.getComputedStyle(rootElement);

// Get the value of the custom property
const primaryColor = computedStyles.getPropertyValue('--primary-color').trim();

console.log(primaryColor);

Using .trim() is best practice because getPropertyValue() often returns strings with leading whitespace.

Modifying CSS Custom Properties

To update or define a custom property on an element, use the setProperty() method on the element’s style property. This writes an inline style to the element, which takes precedence in the cascade.

// Setting a variable globally on :root
document.documentElement.style.setProperty('--primary-color', '#ff5722');

// Setting a variable on a specific element
const card = document.querySelector('.card');
card.style.setProperty('--card-padding', '24px');

Setting a property on document.documentElement updates the variable for the entire page, instantly triggering a repaint for any descendant elements referencing that variable via var(--primary-color).

Removing CSS Custom Properties

To revert an element’s custom property back to its stylesheet or inherited default, remove the inline declaration using removeProperty().

// Removes the inline override, falling back to CSS rules
document.documentElement.style.removeProperty('--primary-color');

Advanced Interaction: CSS Typed Object Model

Modern browsers support the CSS Typed Object Model (Typed OM), which provides a higher-performance, typed interface for interacting with CSS properties instead of parsing strings.

Using the CSSOM to manipulate custom properties decouples application logic from presentation, allowing JavaScript to manage state while CSS handles rendering and layout updates efficiently.