What is CSS Variable ?
Last Updated :
16 Feb, 2024
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);
}
Share your thoughts in the comments
Please Login to comment...