CSS Custom Property Basics

What are Custom Properties?

One of the simplest yet most useful features of CSS pre-processors such as SASS is variables. Being able to share a value across a codebase and keeping stylesheets DRY makes maintenance easier, intention clearer and helps to prevent logically identical values from becoming inconsistent.

CSS custom properties provide native support for similar variables but with the advantage that their values may be modified at runtime allowing powerful but easy style changes.

Declaring a Custom Property

Custom properties are declared just like any other CSS declaration but the property must have two dashes prefixed. The property can have any name you like. To use the custom property as a value simply include its name inside var().

:root {
  --mycustomprop: #ff0000;
}

p {
  color: var(--mycustomprop);
}

Testing Custom Property Support

Custom property support can be tested in either CSS using an @supports feature query or via the CSSOM with CSS.supports.

@supports (--mycustomprop: #ff0000) {
/* styles */
}
const support = CSS.supports('--mycustomprop: #ff0000');

Modifying Custom Properties at Runtime

To modify a custom property at runtime simply use the style.setProperty function of the element for which you would like to change the custom property’s value.

document.documentElement.style.setProperty('--mycustomprop', '#00ff00');

This is really flexible as you can either change the custom property’s value in the scope it was initially declared (as above) or you can change the value at any point in the cascade (by targeting a child element) to limit the scope of the changed value.

Example

The example below features a box and some text which use a custom property defined in the document root. When the colour input’s value is changed the custom properties value is changed via JavaScript.

Conclusion

Custom Properties are perfect for scenarios where you would like the user to have some level of control of application style. For example I have an option in my Chrome extension Furigana Toggle which shows words on the page the extension can affect in colour - I allow the user to select this colour in case the default colour clashes with the other colours on a given page.

Unlike pre-processor variables custom properties provide flexibility at runtime which opens up new possibilities for dynamic styling.

CSS JavaScript Web
SCROLL TO TOP