CSS Custom Properties (Native FWT)

CSS Variables

Introduction

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.

Usage

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);
}

Examples

Internationalization demo

A real-world example of CSS variables usage is easily separating out strings from where they’re used, to aid in maintenance of internationalization;

Interactive demo: under index.html tab, change the lang=".." (ar, ru, or none) attribute

Theme management demo

See the Pen vzKwMZ by Mahmoud Elmahdi (@elmahdim) on CodePen.

Browser compatibility

css variables - caniuse.com

Further details can be found here: https://caniuse.com/#search=CSS%20Variables