CSS ยท Chapter 36 of 44
CSS Variables
CSS custom properties (variables) let you store reusable values, defined with a double-dash prefix like --main-color, and accessed using the var() function.
Variables are typically declared on :root for global scope, making theme changes and consistency much easier to manage.
Syntax
:root {
--main-color: #264de4;
}
color: var(--main-color);Declaring and using variables
Define with --name: value; and use with var(--name). Variables can hold colors, sizes, fonts, or any CSS value.
Scope and fallback values
:root scopes a variable globally. var(--name, fallback) provides a fallback if the variable isn't defined. Variables can also be scoped to specific elements.
Example 1 (css)
:root {
--primary: #264de4;
--spacing: 16px;
}
.btn {
background: var(--primary);
padding: var(--spacing);
}Output
The button uses the shared blue color and spacing value from the root variablesBoth the color and spacing come from centrally defined custom properties.
Key points
- Custom properties are declared with a double-dash prefix (--name).
- var(--name) retrieves a variable's value.
- :root scopes variables globally across the page.
- var() supports a fallback value as a second argument.
๐ก Note: Unlike Sass variables, CSS variables can be changed dynamically at runtime with JavaScript.
