CSS Variable Simplified [2022]

CSS variables are used to define custom properties while styling a web page. It is advisable when the project is large and involves reusable properties or values. It can also be used when defining specific rules for the project theme. It uses var() function while accessing but uses the -- (double dash) notation while declaring or setting it. NB: it is case-sensitive. For Example:

// to set
element {
--main-background: #457839;
}
//to access it
p {
 color: var(--main-background);
}

If you look at the above example, it will be easier to remember "main-background" than "#457839". One of the fun of CSS variables is that you can limit their scope to either local or global.

That is, the local scope will only be limited to a particular element while the global scope will make it accessible to all elements. Also, custom properties are subject to the cascade and inherit their value from their parent. That is, if there's a nested element, that has no property declaration, it can inherit its properties from the parent element.

Usage

The best approach is to declare your custom properties on the :root pseudo-class so that they can be applied globally across your HTML document.

For Example:

:root{
--background: #893200;
--color: #782002;
}

So, anywhere in the styling that you need to call for background all you need to do is introduce the var(--background); and you are good to go. for example:.div { background-color: var(--background);


Fallback value in Custom Properties This is a way of having a substitute value if the custom property is not yet declared. The fallback function only accepts two parameters. The first parameter is the custom property, while the second parameter is the fallback value.

// blue if --section-bg is not defined
.nav {
  background-color: var(--section-bg, blue);
}

// blue if --nav-bg and --section-bg is not defined
.footer {
  background-color: var(--nav-bg, var(--section-bg, pink));
}

//Invalid
.section {
  background-color: var(--nav-bg, --section-bg, pink);
}

Fallback values are not used to resolve browser compatibility issues. The fallback value won't assist if the browser doesn't allow CSS custom properties. If the provided variable isn't specified or has an invalid value, it's only a backup for the browser that supports CSS custom properties to choose a different value.

I hope this helps you as you continue your dev journey. See you soon πŸ‘‹