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:
xxxxxxxxxx
1
:root {
2
--variable-name: yellow; /* <--- global variable declaration */
3
}
4
5
.element-1 {
6
color: var(--variable-name); /* <--- global variable usage example */
7
}
8
9
.element-2 {
10
background: var(--variable-name); /* <--- global variable usage example */
11
}
Warning:
var
keyword was introduced in major web browsers around 2016-2017.
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.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
:root {
7
--main-color: red; /* <--- global variable declaration */
8
}
9
10
.element-1 {
11
color: var(--main-color); /* <--- global variable usage example */
12
}
13
14
.element-2 {
15
border: 1px solid var(--main-color); /* <--- global variable usage example */
16
}
17
18
.element-3 {
19
background: var(--main-color); /* <--- global variable usage example */
20
}
21
22
</style>
23
</head>
24
<body>
25
<div class="element-1">Example text...</div>
26
<br />
27
<div class="element-2">Example text...</div>
28
<br />
29
<div class="element-3">Example text...</div>
30
</body>
31
</html>