Skip to main content

Introduction to CSS Variables

import CustomEditorHTML from "@site/src/components/CustomEditorHTML";

CSS Variables

CSS variables, also known as custom properties, allow you to define a value once and reuse it throughout your CSS. They are declared using the -- prefix followed by a name and a value.

As an example:

:root {
--main-color: #007bff;
}

In this example:

  • We're defining a variable named --main-color with a value of #007bff.
  • The :root selector specifies that this variable should be available to all elements in the document.

You can use this variable to set the color of an element like this:

button {
background-color: var(--main-color);
}

In this example:

  • We're using the var() function to reference the --main-color variable.
  • This will set the background color of all buttons to the value of the --main-color variable, which is #007bff.

CSS variables can also be used to create more complex styles:

:root {
--main-color: #007bff;
--main-background: var(--main-color);
--main-border: 2px solid var(--main-color);
}

button {
background-color: var(--main-background);
border: var(--main-border);
}

In this example:

  • We're defining three variables: --main-color, --main-background, and --main-border.
  • The --main-background variable references the --main-color variable, and the --main-border variable uses the var() function to include the --main-color variable in a border declaration.
use variables

You can create more modular and maintainable CSS styles, and easily update the appearance of your website or application by changing the value of a single variable.

How var() Works

The var() function in CSS is used to reference a CSS variable or custom property. It allows you to use the value of a variable in a CSS property value.

The syntax of the var() function is as follows:

var(<variable-name>, <default-value>)

In this example:

  • <variable-name> is the name of the CSS variable or custom property you want to reference, without the -- prefix.
  • <default-value> is an optional value that is used if the referenced variable is undefined.

As an example:

:root {
--main-color: #007bff;
}

button {
background-color: var(--main-color, red);
}

In this example:

  • We're defining a CSS variable named --main-color with a value of #007bff.
  • We're then using the var() function to set the background color of a button element to the value of the --main-color variable.
  • If the --main-color variable is not defined, the background color will be red.