Dark mode
While this site is new and super-simple, I thought I add an automatic “dark mode” real quick.
With “automatic” I mean, when your operating system is configured to prefer a dark appearance, this website will follow suit. There’s currently no other way to toggle this.
And I’m using CSS variables to implement this. I’ve used different approaches before, but this time I wanted to try this seemingly popular solution.
Basically what I did was putting all my colour definitions into one CSS variable each and declare those within the :root
selector:
:root {
color-scheme: light dark;
--background-color: #F9F9F9;
--header-background-color: white;
--text-color: #222;
/* etc. */
}
Then, you can overwrite the variables’ values further done in the file for when the OS prefers a dark colour scheme:
@media (prefers-color-scheme: dark) {
:root {
--background-color: #222;
--header-background-color: #111;
--text-color: #dddddd;
/* etc. */
}
}
CSS Variables enjoy good support right now, but I still decided to offer a fallback for browsers that do not support them. That way my default (bright) theme will render properly in all browsers. So, all CSS rules that use variables will always have a fallback. Like so:
background-color: #F9F9F9;
background-color: var(--background-color);
To get rid of the duplicate variable declarations, I use SCSS variables to only define them once. For the final CSS file, those SCSS variables will of course be replaced and converted into actual values during the “build” step of this site. So a complete source example actually looks something like this:
/* SCSS variable definitions */
$background-color: #F9F9F9;
/* ... */
/* CSS variable definitions */
/* Using the SCSS variables as the source */
:root {
color-scheme: light dark;
--background-color: #{$background-color};
/* ... */
/* CSS variable definitions for dark mode */
@media (prefers-color-scheme: dark) {
--background-color: #222;
/* ... */
}
}
/* Usage with a fallback. */
body {
background-color: $background-color; /* using the SCSS variable as a fallback, which will get replaced for the final CSS stylesheet */
background-color: var(--background-color);
/* ... */
}
Using CSS variables of course means that browsers without support won’t be able to “see” the dark site. But as far as I know, operating systems that offer “Dark Mode” are so up-to-date right now, that their (default) browsers will, too. So, there’s really nothing to lose here. Until I maybe add another option to toggle dark mode manually. But that’s a topic for another day.