Course contentsShow
← Web Development
Lesson 476 of 2,9828. Advanced CSS Selectors and FeaturesFree lesson

Custom Properties and JavaScript

Reading and setting custom property values dynamically with getPropertyValue and setProperty.

Custom Properties and JavaScript

What You'll Learn

You'll learn how to read and update CSS custom property values dynamically using JavaScript, creating interactive styles that respond to user actions or application state.

Bridging CSS and JavaScript

CSS custom properties aren't just static values — they're living variables that JavaScript can read and modify in real-time. This creates a powerful connection between your logic and your styles.

JavaScript accesses custom properties through the CSSStyleDeclaration interface, which every element's style object implements.

Reading Custom Property Values

To read a custom property, use getComputedStyle() to access an element's final computed styles, then call getPropertyValue():

// Get the value of --main-color from the root
const rootStyles = getComputedStyle(document.documentElement);
const mainColor = rootStyles.getPropertyValue('--main-color');
console.log(mainColor); // e.g., "#3498db"

Think of getComputedStyle() as asking the browser, "What does this element actually look like right now?"

Setting Custom Property Values

To change a custom property, use the element's style.setProperty() method:

// Change --main-color on the root
document.documentElement.style.setProperty('--main-color', '#e74c3c');

// Or scope it to a specific element
const card = document.querySelector('.card');
card.style.setProperty('--card-padding', '2rem');

Because custom properties cascade, changing a value on :root instantly updates it everywhere that variable is used — no need to hunt down every element!

Practical Use Cases

This technique powers interactive features like theme switchers, dynamic color adjustments based on user input, or animations driven by scroll position.

Key Takeaway: JavaScript can read custom properties with getPropertyValue() and update them with setProperty(), creating a two-way bridge between your styles and application logic that updates instantly across your entire page.