1
mirror of https://github.com/jakejarvis/jarv.is.git synced 2025-04-26 15:28:28 -04:00
jarv.is/notes/dark-mode.mdx
2022-01-18 13:54:12 -05:00

9.8 KiB

title, date, description, tags
title date description tags
How To: Add Dark Mode to a Website 🌓 2021-10-15 08:56:33-0400 Simple dark mode switching using local storage, OS preference detection, and minimal JavaScript.
JavaScript
NPM
CSS
Dark Mode
How To
Tutorial

Love it or hate it, it seems that the dark mode fad is here to stay, especially now that more and more devices have OLED screens that display true blacks... which means that these trendsetters might go blind from your site's insanely white background if you're behind the curve and don't offer your own dark mode.

It is possible to use pure CSS3 media queries to do this by reading a user's system and/or browser preference, which might be enough if you're okay with only supporting the latest, cutting-edge browsers and OSes. But if you want your own button on your website that switches back and forth between the two modes, there's no avoiding getting your hands a little dirty with some JavaScript.

I've written a simple implementation below, which...

  • Defaults to a user's system preference, until they press your toggle to set it themselves
  • Listens for clicks on any element of your choosing — just set the class to dark-mode-toggle. For example:
<button class="dark-mode-toggle">💡 Switch Themes</button>
  • Remembers the visitor's preference between visits using the local storage of the their browser (not cookies, please don't use cookies!)
  • Switches your <body>'s class between light and dark...

...meaning that any CSS selectors beginning with body.dark or body.light will only apply when the respective mode is active. A good place to start is by separating any color rules — your background, text, links, etc. — into a different section of your CSS. Using SASS or SCSS makes this a whole lot easier with nesting but is not required; this was written with a KISS mentality.