Languages
[Edit]
EN

CSS - declaring global CSS variables

3 points
Created by:
Fletcher-Peralta
778

In this article, we would like to show you how to declare and use global variables in CSS.

Quick solution:

:root {
    --variable-name: yellow;           /*   <--- global variable declaration    */
}

.element-1 {
    color: var(--variable-name);       /*   <--- global variable usage example  */
}

.element-2 {
    background: var(--variable-name);  /*   <--- global variable usage example  */
}

Warning: var keyword was introduced in major web browsers around 2016-2017.

 

Practical example

To declare a global variables we use :root pseudo-class. Within the curly braces, we set a custom properties whose names should be started with a double hyphens (--). Then we can use the global variable inside other selectors with a var keyword as we did in element-1, element-2 and element-3 class styles. 

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    :root {
        --main-color: red;                    /*   <--- global variable declaration     */
    }

    .element-1 {
        color: var(--main-color);             /*   <--- global variable usage example   */
    }

    .element-2 {
        border: 1px solid var(--main-color);  /*   <--- global variable usage example   */
    }

    .element-3 { 
        background: var(--main-color);        /*   <--- global variable usage example   */
    }

  </style>
</head>
<body>
  <div class="element-1">Example text...</div>
  <br />
  <div class="element-2">Example text...</div>
  <br />
  <div class="element-3">Example text...</div>
</body>
</html>

 

References

  1. :root - CSS: Cascading Style Sheets | MDN
  2. Using CSS custom properties (variables) | MDN

Alternative titles

  1. CSS - custom global variables using :root pseudo class
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join