What are custom properties in CSS?

·

2 min read

What are custom properties in CSS?

In CSS3, a feature called custom properties or CSS variables was introduced. This feature enables developers to define variables that can be reused.

In a large project, we apply the same styles in many places, like a color used in many places. Now, suppose there is a requirement to change the color, then we have to replace the color in all places where it has been used. It is tedious and time-consuming.

Example:

.selector1 {
   color: "#aaa";
}
.selector2 {
   color: "#aaa";
}
.selector3 {
   color: "#aaa";
}

In this example, the same color has been used in three places. If we want to change it, then we have to update in all places.

The custom properties solve this problem by defining the color in a single place and using it wherever we want.

:root{
  --mycolor: "#aaa";
}

.selector1 {
   color: var(--mycolor);
}
.selector2 {
  color: var(--mycolor);
}
.selector3 {
   color: var(--mycolor);
}

syntax

A custom property is prefixed with a double dash(--). Example:

  --main-color: blue;
  --secondary-color: black;
  --card-padding: 8px;

How to use them

To use a custom property, We use the var() function. For example:

.container {
   background-color: var(--main-color);
}

Fallback value

The var() function takes two parameters:

  1. Reference to a custom property.

  2. A fallback value (optional). If the first parameter is undefined or invalid, the fallback value is used.

Example:

:root{
  -- main-color: blue;
}

.selector1{
    background-color: var(--main-color, green);  
}

In this example, the var() function uses the first parameter (--main-color) if it is available, otherwise, it uses the fallback color( green ) as the background color of the .container.

Scope of custom properties

A custom property can have global scope or local scope.

Global scope:

We can define global properties in the :root pseudo-class, and then we can access it across the whole HTML document. We can use them inside any selector.

Example:


:root{
  --main-bg-color: blue;
  --primary-color: "#ccc";
  --text-light-grey: "#aaa";
}

.selector1{
  background-color: var(--main-bg-color);
}

.selector2{
  color: var(--text-light-grey);
}

Local scope:

A custom property that is defined within a selector can be accessed within that selector and its children. We can't access it outside of that selector.

Example:

.selector1 {
  /* local scoped variable */
  --bg-color: red;

   background-color: var( --bg-color);
}

.selector2 {
  /* Wrong!  can't access local scoped variable  */
   background-color: var(--bg-color);
}

summary

  • Using CSS custom properties (also known as variables) can help improve code reusability.

  • We can define global properties within the : root pseudo-class

  • To use custom properties, we use the var() function.