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.