CSS Variables ( Custom Property)

We can create variables in CSS to insert custom properties in our stylesheet. For example : If we want to use a particular color for a text for multiple elements, we can store that color in a variable and use that variable wherever we want that color.

Syntax for creating a CSS variable:

Variable declaration in CSS starts with – –(double dash) , you can create local as well as global variables.

Global variables are created under :root or :body selector and the custom property defined under this variable can be used on any element.

Local variables are local to the CSS selector that they are created inside.

To use the declared variable, there is var() function which inserts the value of the variable(custom property) to the stylesheet. Syntax of var() function is as follows:

* var(variable_name, value) where variable_name is required and value is optional.

Example 1:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        :root{
            --main-text-color: red;
        }
        h1{
            --bg-color:yellow;
            background-color: var(--bg-color);
            color:var(--main-text-color);
        }
        p{
            background-color: var(--bg-color);
            color:var(--main-text-color);
        }
    </style>
</head>
<body>
    <h1>CSS VARIABLES</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Deleniti sapiente aliquid nobis? 
        In asperiores laborum autem, et facilis enim numquam non assumenda nobis eligendi. 
        Ullam debitis laboriosam maiores ex voluptate?</p>
    <ul>
        <li>HTML</li>
        <li>CSS</li>
        <li>Javascript</li>
    </ul>
</body>
</html>
Output of the above code

The above example defines a local variable(custom property) – – bg-color under h1. This variable can be used inside h1 only. If we try to access this variable inside p using the var() function, it does not do anything.Only h1 background color is changed. – – main-text-color is defined under :root and it is a global variable. It can be accessed anywhere and text color for p and h1 both is changed to red.

You must be thinking instead of using the variable name we could have used the color name. Why do we create a variable unnecessarily? The answer is, to create once and use anywhere. Otherwise If I want to change the text color of the elements from red to blue, then I will have to change it everywhere one by one and I may miss some elements. With the use of variables , I just have to change the value of that particular variable and that is it.

For Custom Property Cascade please refer to the following link:

Leave a Reply

Your email address will not be published.