CSS Variables

By | October 3, 2021

In this Advance CSS tutorial, we will be going to cover the concept of Variables in CSS.

Create CSS Custom Properties using Variables

Like programming languages, we can use the concept of variables in CSS. A variable in CSS is used to store a property value to access the value using the variable name. To access the variable value, we use the var() function and the variable name as a parameter.

Vamware

<Note>: Old browser versions do not support the var() function, so make sure that you have the latest browser version.

How to create and use a variable in CSS

To create a variable, we should put two dashes (–) before the variable name and assign it a value that it is supposed to store.  The variable name can be arbitrary, but it should be related to the value for readable code.

The variable must be defined or declared inside the selector. The scope of a variable will be limited to the specified selector. If you want to make a variable that can be accessed through all the CSS selectors, then declare the variable in :root or body selector.

To access the variable value, we have to use the var() function and the variable name as a parameter.

Syntax

declaring variable
{--variable_name: value}
accessing variable
{property : var(--variable_name)}

Example

<!DOCTYPE  html>
<html>
<head>
    <title></title>
    <style>
        :root{
            /*colorvariable is a global variable so it can be accessed by any selector*/
            --colorvariable: red;
            }

        #p1{
            /*p1_color_variable scope is limited to p1 only*/
          --p1_color_variable: white;

          /*only p1 can access the p1_color_variable*/
          color: var(--p1_color_variable);

            /*p1 can access colorvariable defined at :root*/
          background-color: var(--colorvariable);
        }

        #p2{
            /*p2_color_variable scope is limited to p2 only*/
          --p2_color_variable: lightblue;


         /*p2 can also access colorvariable*/ 
          color: var(--colorvariable);

        /*only p2 can access the p2_color_variable*/
          background-color: var(--p2_color_variable);
        }
    </style>
</head>
<body>
    <p id="p1">Paragraph 1</p>
    <p id="p2">Paragraph 2</p>
</body>
</html>

CSS variable Summary

  • The variable must be declared within the selector.
  • If a variable is not declared in the :root or body selector, then it will be limited to that selector only.
  • If a variable is declared in the :root or body selector than any other selector can access that variable using var() function.
  • To declare a variable, use the double dash (–) before the variable name.
  • To access the variable, use the var(--variable_name ) function and variable name.

People are also reading:

Leave a Reply

Your email address will not be published. Required fields are marked *