Usage of var() CSS function

The var() function in CSS is used to insert the value of custom properties (CSS variables) into your stylesheet. It provides a way to reuse values throughout your CSS and create more maintainable code.

Syntax

var(--custom-property-name, fallback-value)

Possible Values

Parameter Description
--custom-property-name The name of the custom property (must start with two dashes)
fallback-value Optional value to use if the custom property is not defined

Example: Basic Usage

The following example demonstrates how to define custom properties and use them with the var() function −

<!DOCTYPE html>
<html>
<head>
<style>
    :root {
        --primary-color: #3498db;
        --secondary-color: #2ecc71;
        --text-color: white;
        --padding: 20px;
    }
    
    .card {
        background-color: var(--primary-color);
        color: var(--text-color);
        padding: var(--padding);
        border-radius: 8px;
        margin: 10px;
        width: 250px;
    }
    
    .success {
        background-color: var(--secondary-color);
    }
</style>
</head>
<body>
    <div class="card">
        This is a blue card using CSS custom properties.
    </div>
    
    <div class="card success">
        This is a green success card.
    </div>
</body>
</html>
Two cards appear on the page: the first is blue with white text, and the second is green with white text. Both have 20px padding and rounded corners.

Example: Using Fallback Values

You can provide fallback values in case a custom property is not defined −

<!DOCTYPE html>
<html>
<head>
<style>
    .box {
        width: 200px;
        height: 100px;
        background-color: var(--undefined-color, #ff6b6b);
        color: var(--text-color, black);
        padding: var(--spacing, 15px);
        text-align: center;
        line-height: 70px;
        border-radius: 5px;
    }
</style>
</head>
<body>
    <div class="box">
        Fallback Colors Applied
    </div>
</body>
</html>
A red box with black text and 15px padding appears, using the fallback values since no custom properties were defined.

Conclusion

The var() function enables the use of CSS custom properties, making stylesheets more maintainable and flexible. Always include fallback values to ensure your design works even when custom properties are undefined.

Updated on: 2026-03-15T13:18:34+05:30

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements