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).


Article originally posted on LinkedIn.

Responses

Latest from Web Engineering see all

JavaScript: in depth practical explanation on closures. | cover picture
JavaScript: in depth practical explanation on closures.
Created on 21 July 2018.
A deep look at JavaScript closures with explanations and hands-on code examples.
JavaScript: differences between using var, let and const. | cover picture
JavaScript: differences between using var, let and const.
Created on 19 June 2018.
A close look and explanation at how to properly use the new ES6 JavaScript variable declaration keywords.
JavaScript: how to find a key-value pair in a nested object. | cover picture
JavaScript: how to find a key-value pair in a nested object.
Created on 17 June 2018.
How to recursively traverse a JavaScript nested and unordered object to find if a value exists at a specific key.
×