Dark Mode on AJ.dev
31 Jan 2020 by AJ
Just upgraded AJ.dev to support Dark Mode! Just a quick run down for how I did it.
Media Queries
I learned about prefers-color-scheme
from CSS Tricks. I set up the two essential queries below.
@media (prefers-color-scheme: light) {
/* light background, dark foreground */
}
@media (prefers-color-scheme: dark) {
/* dark background, light foreground */
}
Then I copied all the CSS tags with colors down into these two brackets and filled out the light/dark alternatives. I primarily just inverted colors from the previous background/foreground, plus a little help from ColorHexa.
Light/Dark Image
The only thing left after CSS colors was changing the logo of AJ.dev to be visible in Dark Mode. To do so, I created a second version of the logo using Affinity Designer.
Then in my index.md
file I updated the contents to add a second image, plus I added two CSS classes - one for light mode and one for dark.
<img src="aj-sketch.png" width="300" class="aj-sketch">
<img src="aj-sketch-dark-mode.png" width="300" class="aj-sketch-dark">
Then back in the CSS, I added the following to my media queries:
@media (prefers-color-scheme: light) {
.aj-sketch{
display: block;
}
.aj-sketch-dark{
display: none;
}
/* ... */
}
@media (prefers-color-scheme: dark) {
.aj-sketch{
display: none;
}
.aj-sketch-dark{
display: block;
}
/* ... */
}
These queries will hide/show the correctly tinted images with the theme.
Profit
The results? A beautiful dark theme that changes easily with macOS Appearance 🎉
Awesome right!? Let me know what you think about the theme @ajkueterman on Twitter, or shoot me suggestions for any changes I could make to get it perfect.
Update - September 2021
I recently updated how dark mode works on my site, opting to allow users to toggle between the modes rather than only rely on prefers-color-scheme
. I used <dark-mode-toggle>
to accomplish this, and refactored my dark/light css into their own files. The result is that the site opts for your preferred color scheme, but can be overridden by the toggle in the footer. Check it out below!