9.9 KiB
export const frontmatter = { 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 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 betweenlight
anddark
...
...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.