I hate when code gets repetitive for no good reason. This is especially the case when I write CSS (repeating color codes, corner radiuses, etc.). Some time ago I found out about CSS variables which is really a game changer for my CSS.
Instead of writing:
button {
background-color: #5e79ff;
}
.info-box {
background-color: #5e79ff;
}
You can replace the repeating part with a variable:
:root {
--primary-color: #5e79ff;
}
button {
background-color: var(--primary-color);
}
.info-box {
background-color: var(--primary-color);
}
Now there is a central place to edit the primary color. Of course, variables can also be used for distances and other values.
Variables are passed down to all elements via inheritance.
:root
is a pseudo class to represent to most root element, even above html
.
In other words, what’s defined here is inherited by all elements.
Dark-Mode
Implementing Dark-Mode using variables is a very clean and straight-forward approach:
:root {
--background-color: #efefef;
--primary-color: #9ea3ff;
--text-color: #121212;
}
@media (prefers-color-scheme: dark) {
:root {
--background-color: #121212;
--primary-color: #5e79ff;
--text-color: #efefef;
}
}
body {
background-color: var(--background-color);
color: var(--text-color);
}
button {
background-color: var(--primary-color);
}
.info-box {
background-color: var(--primary-color);
}
The definition in @media (prefers-color-scheme: dark)
is used when the browser is used in dark mode.
Alternatively, you can use just a .dark
class and let the user toggle it using JavsScript: See simple Dark-Mode Example with Toggle-Button.
I hope this simple trick helped you to make your CSS code less repetitive.