Accessible CSS-Only Light/Dark Toggles (with JS persistence as progressive enhancement)

CSS’s :has() can obviate JS
Astronomy: a view of London in 1748, with diagrams of an eclipse. Engraving
Astronomy: a view of London in 1748, with diagrams of an eclipse. Engraving. Wellcome Collection. Public Domain Mark. Source: Wellcome Collection.

Featured in CSS Weekly

This article was featured in CSS Weekly Issue #584

The traditional method of giving users a toggle to switch a site’s theme (for example between light and dark mode) requires JavaScript. A user’s interaction with a button or dropdown triggers JS which adds a class somewhere, or adds an attribute somewhere, or modifies a piece of state. Thanks to CSS’s :has(), the core functionality can now be done without JS. This article I wrote for Smashing Magazine covers that, plus: how to respect user’s system-wide color scheme preferences and motion preferences; how to change user-agent styles with CSS’s color-scheme property; and one way of implementing cross-page / cross-session persistence as a JS-based progressive enhancement.

Read Setting And Persisting Color Scheme Preferences With CSS And A “Touch” Of JavaScript on Smashing Magazine.

Articles You Might Enjoy

Or Go To All Articles