Open In App

What is CSS Variable ?

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

CSS variables, also known as Custom Properties, allow you to define reusable values in CSS. They provide a way to store values in variables and use them throughout your stylesheets. CSS variables start with -- and are case-sensitive.

Syntax:

/* Declaring a CSS variable */
:root {
--main-color: #3498db;
}

/* Using the CSS variable in styles */
.element {
color: var(--main-color);
}

How to Use CSS Variables:

Declaration: Declare variables inside a selector, often within :root to make them global.

:root {
--main-color: #3498db;
--font-size: 16px;
}

Usage: Use the var() function to reference the variable wherever you want to use its value.

.element {
color: var(--main-color);
font-size: var(--font-size);
}

Fallback Values: You can provide fallback values if the variable is not defined.

.element {
color: var(--main-color, #3498db);
}

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads