What is CSS Variables?
CSS variables, also known as CSS custom properties, are entities defined by CSS authors that contain specific values to be reused throughout a document. They are similar to variables in programming languages, allowing you to store information to be referenced and reused multiple times within a stylesheet.
CSS variables are declared using the --
prefix followed by a name, and their values can be any valid CSS value.
For Example:
:root {
--main-color: #ff0000;
}
In this example, --main-color
is a CSS variable storing the color value #ff0000
.
Once defined, CSS variables can be used anywhere in the stylesheet by referencing them with the var()
function.
For Example:
.element {
color: var(--main-color);
}
This would apply the color stored in the --main-color
variable to the text color of elements with the class .element
.
One of the primary benefits of CSS variables is that they allow for more dynamic and flexible stylesheets. They can be updated dynamically using JavaScript, making it easier to implement themes, adjust styles based on user interactions, or maintain consistency across a large codebase by centralizing values.