DEV Community

Cover image for CSS Custom Properties (Native FWT)
Mahmoud Elmahdi
Mahmoud Elmahdi

Posted on

CSS Custom Properties (Native FWT)


A style sheet consists of a list of rules, and many of theme might contain duplicate data; for instance an application may establish a color scheme and resume 3+ colors, or the size of the gutter (gap) between columns throughout the application. Altering this data can be excruciating and fallible. Modern CSS has a powerful feature called CSS Custom Properties (AKA CSS Variables); this feature allows us to get things done more elegantly (Native FWT).

Custom properties --*

CSS variables are prefixed with --, like --color-primary, represent custom properties that contain a value that can be reused throughout the application using the var() functional notation.

Unlike other CSS properties, custom property names are case-sensitive.


Declaring and using variable:

:root {
  —color-primary: tomato;

h1 {
  color: var(—color-primary);

button {
  background-color: var(--color-primary);

A common use case is to define variable(s) in the :root pseudo-class and then use it wherever the value is needed to halt some instances of repetition.

Custom Property fallback values

Using var() functional notation you can define multiple fallback values when the given variable is not yet defined. The first argument to the function is the name of the custom property (CSS variable) to be substituted. The second argument to the function, if provided, is a fallback value, which is used as the substitution value when the referenced custom property is invalid.

Example: Coral, will be the color value for h2 tag because --color-secondary is not defined

h2 {
  color: var(—color-secondary, coral);

Example: Black is the border color value because both of --color-main and --color-accent are not defined

blockquote {
  border-left-color: var(--color-main, var(--color-accent, black));

Example: Invalid number of arguments

footer {
  background-color: var(--color-a, --color-b, red);


For this article I’ve prepared two examples: Internationalization (a real-world example of CSS variables usage), and Theme management; both can be found here (original article)

Browser compatibility

css variables

Further details can be found here (caniuse)

Discussion (0)