What are CSS variables and how they can help you.

A brief introduction on CSS variables, what they are and why they could be really useful for your next front-end project.

The Chicken song rocks, doesn't it? emoji 🐔

Introduction

As you can see by inspecting a little with the Dev Tools in the new YouTube redesigned page (or just watching the video emoji 👍🏽), it highly relies on CSS variables under the hood.

By just changing one CSS variable from the inspector you can change colors (and whatever is set in a CSS variable) all over the entire web page. Imagine how much is now easier to create multiple themes, responsive new layouts and keeping consistency across all your codebase.

CSS variables are a powerful tool which allows you to use variables inside CSS stylesheets without the need of an abstraction layer given by a pre-processor (ex. SASS or LESS).

Why are them so interesting?

  • they inherits! emoji 🙌🏽
  • they can be modified runtime by JavaScript (this is a huge feature). emoji 🏃🏽

How can I recognize and use them? Their syntax is straightforward:

  • prepend the name with two dashes;
  • use it with the
    var()
    function.
/* declaration: */
--variable-name: 30px;

/* usage: */
.my-element{
	padding: var(--variable-name);
}

Can I uninstall SASS? emoji 🚮

It depends, they don’t substitute SASS or LESS, you may still need them for mixins, functions and others additional features.

They are native by the browser and, to date (9/17), they are supported by all the major browsers:

browsers support
browsers support

And IE...?

If you can, give you a favor and update for a ton of sane reasons, from security to UX. emoji 😉

More on this cool stuff here (MDN).


Essay originally published on LinkedIn.

Responses

Latest from Web Engineering browse all

Nested Enums in TypeScript. | cover picture
Nested Enums in TypeScript.
Created August 19 2021.
How to solve the need of nested and multi-level Enums in TypeScript.
WebAssembly + Emscripten Notes. | cover picture
WebAssembly + Emscripten Notes.
Created December 25 2020, updated August 19 2021.
My notes on learning WebAssembly and its integration with Emscripten.
Docker Notes. | cover picture
Docker Notes.
Created November 19 2020, updated December 25 2020.
My notes on learning Docker.
×