A Beginner's Guide to CSS Variables
This article is a beginner-friendly introduction to an advanced Cascading Style Sheets (CSS) concept— CSS variables. CSS variables make your CSS code cleaner and easier to maintain. This article will focus on the following four topics:
- Declaring a CSS variable.
- Using a CSS variable.
- Global and local scopes of CSS variables.
- Overriding a global CSS variable with a local CSS variable.
This article is for web designers and developers who are comfortable with the fundamental CSS concepts such as CSS Syntax, CSS Selectors, and CSS Properties.
Declaring a CSS variable
To declare a CSS variable, use --
followed by a variable name inside a CSS selector.
In the above code, background-light
is the variable name, --background-light
is the CSS variable, and #FAFAFA
is the value assigned to the CSS variable.
Note: CSS variables are case-sensitive. This means --background-light
and --Background-light
are two different CSS variables.
Using a CSS variable
To use the above declared CSS variable, --background-light
, insert it inside the var()
function of a CSS selector.
In the above code, the background-color
property of the body element takes the value of --background-light
variable using the var()
function. In simpler terms, the background color of the body element will be set to #FAFAFA
.
Global and local scopes of CSS variables
A global CSS variable is declared inside the :root
pseudo-selector and can be used throughout the stylesheet document. A local CSS variable is declared inside a particular CSS selector and can be used only inside that selector.
The following code demonstrates the declaration of the global variable, --background-light
, inside the :root
pseudo-selector. It is then used inside the body
selector:
The following example demonstrates the declaration and usage of the local variable, --background-light
:
Overriding a global CSS variable with a local CSS variable
Override a global CSS variable with a local CSS variable by re-declaring the CSS variable within a specific selector you want modified.
The following example demonstrates the overriding of a global CSS variable --background-light
inside the button
selector:
Go beyond the basics
The following links are some excellent resources to learn more about CSS variables.