CSS var() Function

Last Updated : 11 Jun, 2026

The CSS var() function is used to access the value of a custom property (CSS variable). It helps make styles reusable, consistent, and easier to maintain across a webpage.

  • Retrieves the value of a CSS custom property (variable).
  • Allows defining reusable values for colors, sizes, spacing, and more.
  • Supports a fallback value if the specified variable is not defined.

Syntax:

var(custom_property, value)

Parameters:

  • custom_property: The required CSS variable name, which must begin with two dashes (--).
  • value: An optional fallback value used if the custom property is undefined or invalid.

Example: var() function in CSS

html
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
    <title>var() function</title>
<!--Driver Code Ends-->

    <style>
        :root {
            --main-bg-color: Green;
        }

        /* Use of var() function */
        .gfg1 {
            background-color: var(--main-bg-color);
            padding: 10px;
        }

        .gfg2 {
            background-color: var(--main-bg-color);
            padding: 5px;
        }

        h1 {
            color: green;
        }

        body {
            text-align: center;
        }
    </style>

<!--Driver Code Starts-->
</head>

<body>
    <h1>GeeksforGeeks</h1>
    <h2>var() function</h2>
    <div class="gfg1">GeeksforGeeks</div><br>
    <div class="gfg2">
          A computer science portal for geeks
      </div>
</body>
</html>
<!--Driver Code Ends-->
Comment