from Hacker News

Show HN: A Dark Mode Toggle Without JavaScript

by TymekDev on 1/11/24, 8:13 PM with 5 comments

Today I scratched my itch of implementing a dark mode toggle without JacaScript. The implementations I saw typically revolved about adding a 'dark' class to body via JS and then controlling it with JS handlers.

Thanks to `:has()` selector [0], that passed 90% browser compatibility [1], it is possible to avoid JS.

My implementation uses CSS variables combined with a checkbox, `:checked`, and `:has()`. It is simple, yet supports color scheme preference and updates toggle's label based on active mode.

[0]: https://developer.mozilla.org/en-US/docs/Web/CSS/:has

[1]: https://caniuse.com/css-has

  • by DHPersonal on 1/11/24, 8:34 PM

    This is really cool and a great example of the upgrades to CSS. The benefit of JavaScript would be setting a state in localStorage to remember the light/dark value that was set, as yours does not remember what was set after a shift+f5 refresh of the site.
  • by numtel on 1/11/24, 9:54 PM

    I'm sure it'll make it to Firefox for Android soon. I would imagine these "in page" toggles will fade away as the OS makes the switcher more prominent. In Gnome, it's right in the main menu next to the volume.
  • by baobaba on 1/11/24, 8:42 PM

    Thanks for sharing! Very cool.