--- title: "How To: Add Dark Mode to a Website 🌓" date: 2021-10-15 08:56:33-0400 description: "Simple dark mode switching using local storage, OS preference detection, and minimal JavaScript." tags: - JavaScript - NPM - CSS - Dark Mode - How To - Tutorial --- Love it or hate it, it seems that the [dark mode fad](https://en.wikipedia.org/wiki/Light-on-dark_color_scheme) is here to stay, especially now that more and more devices have [OLED screens](https://www.macrumors.com/2019/10/21/ios-13-dark-mode-extends-iphone-battery-life/) 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](https://css-tricks.com/dark-modes-with-css/) 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](https://caniuse.com/#feat=prefers-color-scheme) 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: ```html ``` - Remembers the visitor's preference between visits using the [local storage](https://www.w3schools.com/html/html5_webstorage.asp) of the their browser (not cookies, please don't use cookies!) - Switches your ``'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](https://sass-lang.com/) makes this a whole lot [easier with nesting](https://sass-lang.com/guide#topic-3) but is not required; this was written with a [KISS](https://www.youtube-nocookie.com/embed/O58A7MJfOwU?hl=en&fs=1&showinfo=1&rel=0&iv_load_policy=3) mentality.