EN
CSS - declaring global CSS variables
3
points
In this article, we would like to show you how to declare and use global variables in CSS.
Quick solution:
:root {
--variable-name: yellow; /* <--- global variable declaration */
}
.element-1 {
color: var(--variable-name); /* <--- global variable usage example */
}
.element-2 {
background: var(--variable-name); /* <--- global variable usage example */
}
Warning:
varkeyword was introduced in major web browsers around 2016-2017.
Practical example
To declare a global variables we use :root pseudo-class. Within the curly braces, we set a custom properties whose names should be started with a double hyphens (--). Then we can use the global variable inside other selectors with a var keyword as we did in element-1, element-2 and element-3 class styles.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
:root {
--main-color: red; /* <--- global variable declaration */
}
.element-1 {
color: var(--main-color); /* <--- global variable usage example */
}
.element-2 {
border: 1px solid var(--main-color); /* <--- global variable usage example */
}
.element-3 {
background: var(--main-color); /* <--- global variable usage example */
}
</style>
</head>
<body>
<div class="element-1">Example text...</div>
<br />
<div class="element-2">Example text...</div>
<br />
<div class="element-3">Example text...</div>
</body>
</html>