CSS Variables Tutorial

In this CSS article we want to learn about CSS Variables Tutorial CSS variables also known as custom properties allows developers to define and reuse values across their CSS files. with CSS variables you can create set of global values that can be easily accessed and modified throughout your CSS. in this article we will go over the basics of using CSS variables.

 

 

CSS Variables Tutorial

CSS variables are declared using — syntax. for example to declare a variable named primary-color you would use the following syntax:

 

 

Once you have declared a variable you can use it anywhere in your CSS by referencing it with var() function. for example to use primary-color variable as the background color for an element you would use the following syntax.

 

 

One of the key benefits of CSS variables is that they can be easily modified throughout your CSS. to modify a variable simply redefine it with a new value. for example for changing the primary-color variable to red you would use the following syntax.

 

 

CSS variables can also be accessed and modified using JavaScript. for accessing CSS variable in JavaScript you can use getComputedStyle() function. for example for getting the value of primary-color variable you would use the following syntax.

 

 

For modifying CSS variable with JavaScript you can simply update the value of the variable using the setProperty() function. for example to change the primary-color variable to green you would use the following syntax.

 

 

This is the complete practical example

In this example we declare CSS variable named –primary-color at the :root level and after that use it in different CSS rules throughout the document. we also included a button with an onclick event that calls JavaScript function to change the value of the –primary-color variable to red.

Note that we access and modify the CSS variable in JavaScript using the document.documentElement.style.setProperty() method.

 

 

 

This will be the result

CSS Variables Tutorial
CSS Variables Tutorial

 

 

Learn More on CSS

Leave a Comment