DEV Community

Nathan
Nathan

Posted on

CSS Variables (the basics)

Terminology:

The following terminology will be used in this article when talking about CSS declarations:

  • Selector: Part of the CSS rule outside the curly brackets- tells the browser which HTML elements should have the CSS declarations applied to them. Eg: h1
  • Declaration: A property and value pair, the two are separated by a colon. Eg: color: green;
  • Property: The left side of the declaration, this specifies what to actually style. Eg: color
  • Value: Right side of the declaration, the value can be made up of keywords/values that determine the style applied by the property. Eg: green; CSS Declaration Diagram source:henessyceballos

 
 

What Are CSS Variables?

CSS variables (also known as CSS custom properties or cascading variables), are entities that have been assigned a specific CSS value.
This can be any valid CSS value including, but not limited to:

  • Fonts (eg: times new roman').
  • Colors (eg: #50E3C2).
  • Sizes (eg: 50px).

A CSS variable is normally declared for a value that appears often in the document. Here is an example where many selectors that have the value `blue` assigned to their properties:

div {
 border: 1px solid blue;
 color: blue;
}

h1 {
 background: blue;
}

p {
 color: blue;
}
Enter fullscreen mode Exit fullscreen mode

A CSS variable can store the value blue. The variable can then be reused throughout the document. Should the value blue ever need to be updated, it then only has to be updated in one place- where the variable is declared.

 
 

CSS Variables Syntax

:root {
 --my-variable: red;
}

p {
 color: var(--my-variable);
}
Enter fullscreen mode Exit fullscreen mode

An example of a CSS variable being declared and used- this code renders a p tag with red text.

 

Declaring and Assigning CSS variable:

:root {
  --my-variable: red;
}
Enter fullscreen mode Exit fullscreen mode

CSS variables can be declared on any CSS selector, in the example :root has been used, the reasoning behind this is explained later on. More than one CSS variable can be declared on a selector.

The whole statement to declare and assign a CSS variable should look something like this: --my-property: 200px;

This can be broken down into 3 parts:

  1. The variable name(left side):

    • Variable names must start with the double-hyphen(--).
    • After the double hyphen, any naming convention/casing can be used.
    • --myVariable, --MY_VARIABLE and --my-variable are all valid names.   ⚠️Note: CSS variable names are case sensitive, so these names cannot be used interchangeably.
  2. The colon(separator):

    • The variable name must be followed by a colon(:) before the value can be declared.
  3. The variable's value(right side):

    • Any valid CSS value can be set.
    • Once the value is declared it must be followed by a semi-colon(;)

 

Accessing a CSS variable:

p {
 color: var(--my-variable);
}
Enter fullscreen mode Exit fullscreen mode

When writing a CSS declaration that uses a CSS variable, the property in question (color) does not change. However, the way the value is written does.
The var() function is used to assign the value from a CSS variable to a CSS property, this is done like so:var(--my-variable).
The var() function takes a CSS variable as a parameter, this function call then replaces what would normally be written on the right side of the colon in a CSS declaration.
For example: color: red; would be replaced with color: var(my-variable);

 

CSS Variables- Scope

CSS variables can be declared on any CSS selector. The selector they are declared on determines the scope of the variable. Only the selector (parent) in question, and any child elements of it, will have access to that variable.

For this reason, common best practice is to declare variables in the :root pseudo class. This gives the variables global scope, meaning they can be accessed by any elements in the document.

 

CSS Variables- Inheritance:

CSS variables follow the typical cascade, meaning they inherit values from their parent and can be overwritten further down the document. Below is an example of how CSS variables can be used to overwrite color of link on hover:

:root {
 --link-color: green;
}

a {
 color: var(--link-color);
}
a:hover{
 --link-color: red;
}
Enter fullscreen mode Exit fullscreen mode

If no value is set for a variable on an element, the value will be inherited from that element's parent.

 
 

Why CSS Variables are Useful:

  • They help to avoid repetition, making the code DRYer.
  • It makes it easier to update code - by simply updating the value assigned to the variable in the root, everywhere that variable is used will be updated.
  • They can make code more readable - at a glance it's easier to understand the purpose of --main-bg-color than rgba(23, 24, 56, .8).
  • They can be used to make cool effects pretty easily, in very few lines of code- especially if you throw in a bit of JavaScript like in this CodePen where I made a simple dark-mode toggle:

 
 

Conclusion:

CSS variables allow a value to be stored in one place, so it can be referenced in many other places throughout a document.
These can be really handy in making your CSS cleaner, more efficient and easier to read. You might want to consider using them in your code if you don't already!

 
 

Some Resources:

Some places to find out more about CSS variables:

Top comments (4)

Collapse
 
jmdejager profile image
🐤🥇 Jasper de Jager • Edited

Nice article!
Don't forget the beauty of default values for a css variable.

background-color: var(--background-color, midnightblue)

with this you'll make it possible te have a default but override it if you want to.

I also use css variables in combination with calc() sometimes

margin: 20px calc(20px - var(--some-special-width-var, 0px))

Collapse
 
afif profile image
Temani Afif

in your last example you need to use 0px instead of 0 because the unitless value will make the calc() invalid because calc(20px - 0) is invalid (more detail : stackoverflow.com/a/55406181/8620333)

Collapse
 
jmdejager profile image
🐤🥇 Jasper de Jager • Edited

Thnx! Changed it. So easy to forget the details..

Collapse
 
nathanh profile image
Nathan

Thank you! You make a very good point- always good practice to have a default value.