JAVASCRIPT

Manipulating CSS Custom Properties (Variables) with JavaScript

Learn how to dynamically read and update CSS custom properties (variables) from JavaScript, enabling powerful theme and style customizations for web elements.

function setCssVariable(element, varName, value) {
  element.style.setProperty(`--${varName}`, value);
}

function getCssVariable(element, varName) {
  return getComputedStyle(element).getPropertyValue(`--${varName}`).trim();
}

// Example Usage:
// Assume a CSS variable is defined, e.g., in style.css or <style> block:
// :root { --primary-color: #007bff; --spacing-unit: 1rem; }
// .my-element { background-color: var(--primary-color); padding: var(--spacing-unit); }

// Get a reference to an element, e.g., the root element or a specific div
// const root = document.documentElement; // For global variables
// const myDiv = document.getElementById('myDiv'); // For element-specific variables

// // Set a global primary color
// setCssVariable(root, 'primary-color', '#ff5733');
// console.log('New primary color:', getCssVariable(root, 'primary-color'));

// // Set a spacing unit for a specific div (if defined for it)
// if (myDiv) {
//   setCssVariable(myDiv, 'spacing-unit', '2rem');
//   console.log('MyDiv spacing unit:', getCssVariable(myDiv, 'spacing-unit'));
// }

// // You can also get/set properties that aren't defined directly on the element,
// // but inherited or defined on ancestors (like :root for global vars).
// console.log('Current body font size (example):', getCssVariable(document.body, 'font-size')); // This is not a CSS variable example, but showing getComputedStyle capability
How it works: CSS custom properties (variables) allow developers to define reusable values throughout a stylesheet. This snippet shows how to interact with these variables using JavaScript. The `setCssVariable` function uses `element.style.setProperty()` to dynamically update a custom property's value. The `getCssVariable` function uses `getComputedStyle()` to retrieve the current, computed value of a custom property. This enables powerful runtime theming, animation, and responsive design adjustments directly from JavaScript.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs