Programmers were for years frustrated by the lack of concepts such as variables in CSS. This lead to third party solutions like LESS and SASS.
Modern browsers now support CSS variables. They are a powerful feature in CSS that allow you to store and reuse values throughout your stylesheet.
Syntax and Declaration
CSS variables are defined within a selector, usually within the :root
pseudo-class, which represents the document’s root element and is commonly used for global variables.
The variables are prefixed with --
, followed by the variable name.
Using Variables
Use the var()
function to apply the value of a CSS variable wherever needed.
Scope
When variables are defined in :root
, they are globally accessible throughout the entire document.
Variables can also be defined within a specific selector, making them accessible only within that selector and its descendants.
Fallback Values
CSS variables can have fallback values in case the variable is not defined or the value is invalid.
In this case, if --secondary-color
is not defined, the color #ff6347
will be used.