css - Variables - The var() Function Part 1: Declaring and Using CSS Variables

What Are CSS Variables?

CSS variables are declared using the -- prefix inside a selector (usually :root for global variables). They are then accessed using the var() function.

Example 1: Basic Declaration and Usage

:root {

  --main-color: blue;

  --padding-size: 10px;

}

.box {

  background-color: var(--main-color);

  padding: var(--padding-size);

}

Explanation:

--main-color and --padding-size are declared inside :root, making them available globally.

The var(--main-color) applies the variable value to the background-color.

Example 2: Changing Variable Values Locally

.box {

  --local-color: red;

  background-color: var(--local-color);

}

Explanation:

Variables can be declared inside specific elements for local scope.

Here, --local-color is only available inside .box.