Tutorials Tonight's Logo

CSS VARIABLE


CSS variables are used to store a value that can be used frequently in the HTML document.

The variables are defined by a name preceded by double dash and value is assigned to the variable after a colon. Example: --my-color: teal;

:root{
    --my-color: teal;
}

The variable is defined in a way mentioned above.

Now, to access the variable and to use it in the HTML document we use var() function. Example: color: var(--my-color);

p { 
    color: var(--my-color);
}

Working example:-

<!DOCTYPE html>
<html>
    <head>
        <style>
            :root{ --my-color: teal; }
        </style>
    </head>
<body>
    <h2>Learning about CSS variables.</p>
    <p style="color: var(--my-color)">This paragraph is using the CSS variable.</p>
</body>
</html>
▶ Run the code

CSS variable scope

Any variable that we define in CSS has a scope value. Beyond a variable's scope is not accessible.

We have two type of scope :

  1. Global scope
  2. Local scope


1.) Global scope

A variable which is defined globally can be accessed anywhere in the linked document.

A global variable is defined inside :root selector.

:root{ 
    --my-background: orange;
    --my-padding: 15px;
    --my-margin: 10px;
    }
.box{ 
    background-color: var(--my-background);
    padding: var(--my-padding);
    margin: var(--my-margin);
}
▶ Run the code

2.) Local scope

A variable is defined locally by defining it within the code block of a specific selector.

A local variable can only be used within the selector it is defined.

.box{
    --my-background: orange;
    --my-padding: 15px;
    --my-margin: 10px;
    background-color: var(--my-background);
    padding: var(--my-padding);
    margin: var(--my-margin);
}
▶ Run the code

Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.