The Wayback Machine - https://web.archive.org/web/20250108095036/https://www.geeksforgeeks.org/css-var-function/
Open In App

CSS var() Function

Last Updated : 30 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The var() function in CSS is used to insert a value for a custom property. 

Syntax:

var( custom_property, value )

Parameters: This function accepts two parameters which are listed below:

  • custom_property: It is the required parameter. The name of the custom property must start with two dashes(–).
  • value: It is an optional parameter. It is used if the custom property is invalid.

Example: The below program illustrates the var() function in CSS: 

html
<!-- HTML code to describes var() function in CSS -->
<!DOCTYPE html>
<html>
<head>
    <title>var() function</title>
    <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>
</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>

Output:

  

Supported Browsers: The browser supported by var() function are listed below:

  • Google Chrome 49.0
  • Edge 15.0
  • Firefox 31.0
  • Safari 9.1
  • Opera 36.0

CSS var() Function – FAQs

What does the var() function do in CSS?

The var() function is used to reference custom properties (CSS variables) in your styles, allowing for more manageable and reusable CSS code.

How do you use the var() function in CSS?

Define a variable using –variable-name: value; within a selector (often :root), then use var(–variable-name); wherever you need the value.

Can var() include fallback values?

Yes, var can include a fallback value, such as var(–variable-name, fallback-value);, to be used if the variable is not defined.

What are the common uses of the var() function?

Var is commonly used for defining colors, spacing, fonts, and other recurring values to ensure consistency and ease of updates across a stylesheet.

Is the var() function supported in all browsers?

The var function is supported in all modern browsers, but older versions of Internet Explorer do not support CSS variables.


Similar Reads

three90RightbarBannerImg