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

How Do I Access CSS Variables Using JavaScript?

Linda Hamilton
Release: 2024-11-24 22:22:14
Original
725 people have browsed it

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');
Copy after login

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');
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template