Accessing and Updating CSS Variables Using JavaScript
This guide explains how to control CSS variables (also known as custom properties) using JavaScript. Accessing and setting CSS variables with JavaScript is straightforward and enables dynamic style updates at runtime.
JavaScript lets you read and modify CSS variable values in real time, enabling your styles to react to changes in application state or user interaction.
In this article, we’ll cover:
Prerequisites
A basic understanding of CSS variables is necessary.
How to access and update CSS variables using vanilla JavaScript
There are several ways to access and update CSS variables using vanilla JavaScript (commonly referred to as Vanilla JS). In this section, we’ll focus on the simplest and most widely used approach.
- Use the
window.getComputedStyle()
function to retrieve the current value of a CSS variable. - Use the
document.querySelector()
function to select the element whose CSS variable you want to modify. - Use the element’s
style.setProperty()
method to set a new value for the CSS variable.
Below is a step-by-step example with detailed explanations.
index.html
Explanation
- The following code represents a basic HTML document.
- The
<link>
tag is used to load thestyle.css
file, which contains CSS code. - There is a
<div>
element with the classtarget-element
and a button labeled "Change Styles." - The
<script>
tag includes thescript.js
file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Controlling CSS Variables with JavaScript</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="target-element">
Hello, this is a text with dynamic styles!
</div>
<button type="button" id="changeStylesBtn">Change Styles</button>
<script src="script.js"></script>
</body>
</html>
style.css
Explanation
- Two CSS variables,
--main-color
and--font-size
, are defined under the:root
selector. - The
var()
function is used within the.target-element
class to apply these variables. The text inside the.target-element
class is styled with the color defined by--main-color
and the font size defined by--font-size
.
:root {
--main-color: blue;
--font-size: 16px;
}
.target-element {
color: var(--main-color);
font-size: var(--font-size);
}
script.js Explanation
First, let’s review the example code, followed by a detailed explanation.
// 1. Use window.getComputedStyle() to get the current values of CSS variables.
const rootStyles = window.getComputedStyle(document.documentElement);
const targetElement = document.querySelector(".target-element");
const mainColorValue = rootStyles.getPropertyValue("--main-color");
const fontSizeValue = rootStyles.getPropertyValue("--font-size");
console.log(mainColorValue); // Output: "blue"
console.log(fontSizeValue); // Output: "16px"
// 2. When the "Change Styles" button is clicked, dynamically update the CSS variables to change styles.
document.getElementById("changeStylesBtn").addEventListener("click", () => {
// 3. Use element.style.setProperty() to update the CSS variables.
targetElement.style.setProperty("--main-color", "red");
targetElement.style.setProperty("--font-size", "20px");
});
- The
window.getComputedStyle(document.documentElement)
method is used to retrieve the CSS variable values from the:root
element and store them inrootStyles
. document.querySelector(".target-element")
selects the element with thetarget-element
class and assigns it to thetargetElement
variable.rootStyles.getPropertyValue("--main-color")
retrieves the current value of the--main-color
variable and stores it inmainColorValue
. ThegetPropertyValue()
method accesses the value of a CSS property.rootStyles.getPropertyValue("--font-size")
similarly retrieves the current value of the--font-size
variable and stores it infontSizeValue
.- Logging
mainColorValue
andfontSizeValue
to the console confirms that--main-color
is "blue" and--font-size
is "16px." - Clicking the "Change Styles" button triggers the event listener.
- Inside the event listener,
targetElement.style.setProperty()
is used to update the CSS variables oftargetElement
. - As a result, the text color of
.target-element
changes to red, and the font size updates to 20px.
When you run this code, the page displays the text "Hello, this is a text with dynamic styles!" along with a "Change Styles" button. Clicking the button changes the text color to red and increases the font size to 20px. This demonstrates how to access and modify CSS variables dynamically using JavaScript.
Functions Used in script.js
Below is a list of the main JavaScript functions used in the example script.js
file. These functions are essential for interacting with the DOM and manipulating CSS variables.
window.getComputedStyle()
|
Retrieves computed styles of an element, including CSS variables. |
---|---|
document.querySelector()
|
Selects the first element that matches a CSS selector. |
document.getElementById()
|
Selects an element by its unique ID attribute. |
getPropertyValue()
|
Gets the value of a CSS property from a CSSStyleDeclaration object. |
setProperty()
|
Sets the value of a CSS property on an element’s style. |
How to access and update CSS variables using jQuery
Here’s how to access and update CSS variables using jQuery, based on the previous example written in vanilla JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Control CSS Variables with JavaScript</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="target-element">
Hello, this is a text with dynamic styles!
</div>
<button id="changeStylesBtn">Change Styles</button>
<!-- Load jQuery library -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
:root {
--main-color: blue;
--font-size: 16px;
}
.target-element {
color: var(--main-color);
font-size: var(--font-size);
}
// 1. Use jQuery to get the current values of CSS variables
const mainColorValue = $(":root").css("--main-color");
const fontSizeValue = $(":root").css("--font-size");
console.log(mainColorValue); // Output: "blue"
console.log(fontSizeValue); // Output: "16px"
// 2. When the "Change Styles" button is clicked, dynamically update the CSS variables
$("#changeStylesBtn").on("click", () => {
// 3. Use jQuery to update the CSS variable values
$(".target-element").css("--main-color", "red");
$(".target-element").css("--font-size", "20px");
});
Explanation of jQuery Code (script.js
)
jQuery provides a simpler syntax for selecting elements and modifying styles compared to vanilla JavaScript.
:root
is used as a selector to access global CSS variables.$("selector")
is the jQuery syntax to select elements. For example,$(".target-element")
selects the element with thetarget-element
class.- The
css()
method in jQuery is used to both retrieve and set CSS property values, including custom properties.
When you run the example, the initial values "blue" and "16px" are logged to the console. After clicking the “Change Styles” button, the text color changes to red and the font size increases to 20px. This demonstrates how you can dynamically control CSS variables using jQuery.
Functions Used in script.js
Below is a list of the main jQuery methods used in the example script.js
file. Click any method to view its official documentation on the jQuery website.