CSS Variables (original) (raw)

Last Updated : 04 Jan, 2025

CSS variables (custom properties) are reusable values defined with two dashes (–) that make your CSS code efficient and easier to maintain.

**Syntax

var( --custom-name, value );

**Parameters

<style>
    :root {
        --main-bg-color: lightblue;
        --main-text-color: darkblue;
    }
    body {
        background-color: var(--main-bg-color);
        color: var(--main-text-color);
    }
</style>

Welcome to My Website

This is a sample paragraph demonstrating CSS variables.

`

More Example of CSS Variable

1. Themed Button Using CSS Variables

HTML `

<style>
    :root {
        --button-bg: #4CAF50;
        --button-text: white;
        --button-padding: 10px 20px;
    }
    .btn {
        background-color: var(--button-bg);
        color: var(--button-text);
        padding: var(--button-padding);
        border: none;
        cursor: pointer;
    }
    .btn:hover {
        background-color: darkgreen;
    }
</style>
Click Me

`

**In this example

**2. Dynamic Spacing Using CSS Variables

HTML `

<style>
    :root {
        --spacing: 20px;
    }
    .box {
        width: 100px;
        height: 100px;
        background-color: lightcoral;
        margin: var(--spacing);
    }
</style>

`

**In this example:

Best Practices for CSS Variables