Skip to content

Reuse CSS Values by Using Custom Properties

Custom properties, also known as CSS variables, are defined entities that contain values that can be reused throughout a document. Properties are prefixed with -- as in --property-name and contain values that can be accessed by using the var() function. These can be used for repeating values such as colors that may be challenging to search and replace if changes are needed. Custom properties can be stored in one place and referenced in other places.

A common best practice is to define custom properties on the :root pseudoclass in the Global CSS section so that it can be applied globally throughout the website. However, it’s also possible to limit the scope of a custom property by defining it within an element. Note that property names are case-sensitive, so --this-color will be treated as a separate property to --This-color.

Here’s an example on how to define custom properties in the :root pseudoclass and the property being used in an element:

:root {
    --link-color: red;
    --link-hover-color: pink;
}

a { color: var(--link-color); }
a:hover { color: var(--link-hover-color); }

Inheritance

Custom properties can also be inherited, so if custom property’s value isn’t set on a given element, then the value of its parent is used instead. This is more noticeable for properties that are defined within an element. For instance, take the following HTML:

<div class="parent">
    <div class="child">
        <div class="child-one"></div>
        <div class="child-two"></div>
    </div>
</div>

… And the following CSS:

.child {
    --my-property: 1em;
}

.child-one {
    --my-property: 5px;
}

This means that the value of --my-property will be:

  • 1em for .child
  • 5px for .child-one
  • 1em for .child-two since it’s inherited from its parent .child
  • and invalid for .parent

Fallback

You can also define multiple fallback values through the var() function when a given property is still undefined. The first argument is the name of the property to be substituted. The second one is the fallback value.

.parent {
    /* Only --main-color is defined */
    --main-color: pink;
}

.one {
    /* Since --accent-color is undefined, background will be blue */
    background: var(--accent-color, blue);
}

.two {
    /* Since both are undefined, background will be yellow*/
    background: var(--accent-color, var(--secondary-color, yellow));
}
Scroll To Top