CSS - Variables

CSS Variables

CSS variables are custom properties in which values can be set once and used many times throughout your CSS stylesheet (using its variable name)

  • It makes it easier to manage styles such as colors, fonts, animation, etc.
  • The var() function is used to insert the value of the CSS variable.
  • The syntax is as follows: var(--name, value).
  • name - this is the variable name which must start with double dashes. For example: --bgcolor.
  • value - this is the fallback value, in case the variable specified is not found.

Global Vs Local Variables

Global variables are variables that can be accessed and used through out the entire document, while local variables can only be used inside the selector where it was declared.

  • Global variable is declared inside the :root selector
  • Local variable is declared inside selectors such as (h1, p, .para, div, etc)

How To Use CSS Variable

STEP 1 - Declare the style inside the selector. (Here we are declaring a global variable).

note
NOTE:

The name must begin with double dashes (--)


STEP 2 - Use it inside the appropriate CSS property as shown below.

STEP 3 - All done! Now if we want to change the colors, we don't need to start changing each individual selector styles, all we need to do is simply go to the :root selector and change the color there are shown in the example below.

To Override Global Variables with Local Variables

If there is a particular selector that needs a unique style, all we need do is to re-declare the same variable inside the selector.

Using Variable with JavaScript

Variables can be used with JavaScript to change element's appearance. A simple example is switching from light mode to dark mode.

Using Variable for Customizing Media Queries

You can also use variables to assign different styles for different screen sizes or mobile devices.

tips
TIP:

Variable are very essential in creating website themes, make sure you master how to use them very well; it will help you in future.

ADVERTISEMENTS

LEARNING IS A CONTINOUS PROCESS - PRACTICE MAKES PERFECT