Skip to content
Related Articles

Related Articles

CSS | Variables
  • Last Updated : 14 Jan, 2019

The CSS variables are just like simple variable of any programming language. These variables are used to store values and have a scope in which the variables can be used. A variable is defined by using two dashes(–) at the beginning and then the name which is case-sensitive. The benefit of variables is that it allows the same values to be reused at multiple places and updated/modified from one place. Also, the variable names are easier to understand and use, compared to the values of colors.

Syntax:

var( --custom-name, value )

Parameters: The variable var() accepts two parameters which are listed below:

  • –custom-name It is a required parameter which accepts the custom property name.
  • value: It is an optional parameter. It accepts fallback value which is used when custom property is invalid.

Example 1:




<!DOCTYPE html>
<html>
    <head>
        <title>CSS Variables</title>
          
         <style>
            :root {
                --bg-color: green;
                --txt-color: white;
            }
              
            /* var() function used here */
            body {
                background-color: var(--bg-color);
            }
            h1 {
                color: var(--txt-color);
            }
            div {
                color: var(--txt-color);
            }
        </style>
    </head>
      
    <body>
        <h1>GeeksforGeeks</h1>
          
        <div>
            A computer science portal for geeks
        </div>
    </body>
</html>                    

Output:
CSSVariable



Example 2:




<!DOCTYPE html>
<html>
    <head>
        <title>CSS Variables</title>
          
         <style>
            :root {
                --bg-color: green;
            }
              
            /* var() function used here */
            body {
                background-color: var(--bg-color);
            }
            h1 {
                color: var(--txt-color, white);
            }
            div {
                color: var(--txt-color, white);
            }
        </style>
    </head>
      
    <body>
        <h1>GeeksforGeeks</h1>
          
        <div>
            A computer science portal for geeks
        </div>
    </body>
</html>                    

Output:

Supported Browsers: The browser supported by CSS variables are listed below:

  • Google Chrome 49.0
  • Internet Explorer 15.0
  • Firefox 31.0
  • Safari 9.1
  • opera 36.0
My Personal Notes arrow_drop_up
Recommended Articles
Page :