First thing that we want to do before even considering enabling the dark mode on our web pages is to know whether it is widely or not.
Browser support
When I am writing this post (January 2020), all major browsers (Chrome, Firefox, Safari) but Edge (v76 will be out mid January 2020) support the dark mode, which is around 76.7% of users according to caniuse.com
How to enable the dark mode on your machine ?
You could do that at the OS level or at the browser level. Everything is explained here.
How to detect the dark mode ?
TL;DR: With prefers-color-scheme
prefers-color-scheme
is a CSS media query that allow you to detect if the user has set their system to use a light or dark color theme.
It is really simple to use:
// Fallback for legacy browsers
body {
background-color: white;
color: black;
}
// Used when using the dark theme
@media (prefers-color-scheme: dark) {
body {
background-color: black;
color: white;
}
}
// Used when using the light theme
@media (prefers-color-scheme: light) {
body {
background-color: white;
color: black;
}
}
Use CSS variables for better maintainability
Insted of hardcoding the colors (black
and white
here) we can use CSS variables for better maintainability. All major browsers already support it and 93% of the users are covered according to caniuse.co
Declare a variable
// Use :root pseudo-class to apply anywhere
:root {
--my-variable-color: #CCC;
}
Use a variable
// Will use --my-variable-color value if declared, otherwise #333
p {
color: var(--my-variable-color, #333);
}
If we apply that to our previous example we get the following:
:root {
--light-bg-color: black;
--light-color: white;
--dark-bg-color: white;
--dark-color: black;
}
// Fallback for legacy browsers
body {
background-color: black;
background-color: var(--light-bg-color);
color: white;
color: var(--light-color);
}
// Used when using the dark theme
@media (prefers-color-scheme: dark) {
body {
background-color: var(--dark-bg-color);
color: var(--dark-color);
}
}
// Used when using the light theme
@media (prefers-color-scheme: light) {
body {
background-color: var(--light-bg-color);
color: var(--light-color);
}
}
Apply to isitblackfridayyet.app
I applied the dark mode on isitblackfridayyet.app using this commit: 14b3385063c8e234cf189a120e911018bdacb061 and here is the result on Chrome, Firefox, Opera and Safari:
Thanks for reading.