CSS Variable
CSS Variables, also known as Custom Properties, introduce a way to define reusable values in CSS. They allow you to store values and reuse them throughout a stylesheet, providing more flexibility and maintainability in styling web elements.
Example
/* Creating a CSS variable */
:root {
--main-color: #3498db; /* Define a variable */
}
/* Using the variable */
.element {
color: var(--main-color); /* Use the variable */
}
CSS Variable Notes
-
Syntax : Variables start with
--
and are defined within the:root
pseudo-class to make them global and accessible throughout the document. -
Usage : Variables are accessed using the
var()
function, where you specify the variable name. This function allows you to use the variable value wherever it’s needed. -
Value Inheritance : Variables can be inherited by descendant elements, similar to other CSS properties.
-
Fallback Values : You can provide fallback values in case the variable isn’t defined or supported by the browser.
Example of Fallback Value
.element {
color: var(--main-color, #3498db); /* Use variable with fallback */
}