CSS Variables


CSS Variables

The var() function is used to put the value of a CSS variable into a style.

CSS variables can interact with the web page, allowing you to make variables that work either everywhere or in specific parts. You can also adjust these variables using JavaScript and alter them depending on different screen sizes.

Using CSS variables is a smart idea, especially for managing the colors in your design. Instead of repeatedly copying and pasting the same colors, you can store them in variables.


The Traditional Way

In this example, we demonstrate how to specify colors in a style sheet for different elements using the traditional approach.


Syntax of the var() Function

The var() function is used to put in the value of a CSS variable.

The way you write the var() function is like this:

var(--name, value)
Value Description
name Important. The variable name must begin with two dashes.
value Optional. It's a backup value that gets used when we can't find the variable.

Important: Your variable's name should start with two hyphens (--), and remember, it's sensitive to capitalization!


How var() Works

Firstly, CSS variables can be either global or local in their scope.

Global variables are like tools you can use anywhere in a document, while local variables are more like tools you can only use in a specific area where they're declared.

To make a variable that can be used anywhere, you need to define it within the ":root" selector in your HTML code. The ":root" selector refers to the main element of your document.

To make a local variable, just put it inside the selector where you want to use it.

The next example is just like the one before, but in this case, we employ the var() function.

Initially, we set up two global variables called "--blue" and "--white." Later on, we utilize the var() function to include the values of these variables in our style sheet.

Benefits of using var() include:

  • makes the code easier to read (more understandable)
  • makes it much easier to change the color values

To make the blue and white colors appear softer, you only need to adjust the values of two variables:


CSS var() Function

Property Description
var() Put the number from a CSS variable.