Home >Web Front-end >CSS Tutorial >How Do I Access CSS Variables Using JavaScript?

How Do I Access CSS Variables Using JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-24 22:22:14688browse

How Do I Access CSS Variables Using JavaScript?

How to Access CSS Variables in JavaScript

Accessing CSS variables from JavaScript enables you to dynamically manipulate the styling of your web application. Here's how you can achieve this:

Step 1: Get Computed Styles

Use the getComputedStyle function to retrieve the computed styles of the target element.

Step 2: Get Property Value

Utilize the getPropertyValue method to fetch the value of the desired CSS variable.

Syntax:

getComputedStyle(element).getPropertyValue('--variable-name');

Example:

To retrieve the value of the --color-font-general CSS variable declared in the provided code snippet:

var style = getComputedStyle(document.body);
var color = style.getPropertyValue('--color-font-general');

This code will capture the value of the CSS variable and store it in the color variable.

The above is the detailed content of How Do I Access CSS Variables Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn