To declare a CSS variable, you use a custom property name that starts with two
dashes (--
), followed by a value, inside a CSS selector. The most common
practice is to declare global variables inside the :root
selector so they
can be accessed throughout the entire document. For example:
css
:root {
--main-bg-color: brown;
--main-text-color: white;
}
This declares two CSS variables, --main-bg-color
and --main-text-color
,
with their respective values
. To use these variables elsewhere in your CSS, you reference them with the
var()
function, like this:
css
body {
background-color: var(--main-bg-color);
color: var(--main-text-color);
}
The var()
function can also take a fallback value if the variable is not
defined:
css
color: var(--main-text-color, black);
This means if --main-text-color
is not set, it will default to black
. In summary:
- Declare a variable with
--variable-name: value;
inside a selector (commonly:root
for global scope). - Use the variable with
var(--variable-name)
wherever needed.
Example:
css
:root {
--primary-color: #3498db;
}
h1 {
color: var(--primary-color);
}
This approach makes your CSS more maintainable and reusable