We will typically place variables in a :root pseudo class, since everything will inherit from the root of the document.
A variable is declared by using two dashes, the name of the variable, and a colon. To use the variable in an element we must use the var() function where we want to insert the variable.
/* || VARIABLES */
:root {
/* FONT */
--FONT-FAMILY: "Nunito", sans-serif
--FONT-SIZE: 1.5rem;
--FONT-SIZE-XL: 3rem;
/* COLOR */
--BGCOLOR: #475569;
--DARK: #000
--SHADOWS: 0 6px 5px -5px var(--DARK);
}
body {
background-color: var(--BGCOLOR)
}Note that we can also override the specific value of a variable in a particular declaration. For example, say that we have a series of div elements all with a class of square, except for one that happens to have .square--highlight. We can then do the following:
:root {
--SQUARE-BGCOLOR: black;
}
.square--highlight {
--SQUARE-BGCOLOR: white;
}
.square {
background-color: var(--SQUARE-BGCOLOR);
}This will apply the hwhite color to the specific square we selected, while keeping black on all the other ones.
Dark mode
If we want to create a website that has a dark mode, we can use variables and CSS Media Queries to do so. Assuming we have declared our color scheme with variables under :root, we can then do:
/* ...light color scheme ...
:root {
... some colors ...
--BGCOLOR: #fff
--ALT-BGCOLOR: whitesmoke;
}
*/
@media (prefers-color-scheme: dark) {
:root {
--BGCOLOR: #000
--ALT-BGCOLOR: #333
}
}In effect this is simply overriding the color variables we declared in the root.