Best WordPress Hosting
 

Setting And Persisting Color Scheme Preferences With CSS And A “Touch” Of JavaScript

via smashingmagazine.com => original post link

Many modern websites give users the power to set a site-specific color scheme preference. A basic implementation is straightforward with JavaScript: listen for when a user changes a checkbox or clicks a button, toggle a class (or attribute) on the element in response, and write the styles for that class to override design with a different color scheme.

CSS’s new :has() pseudo-class, supported by major browsers since December 2023, opens many doors for front-end developers. I’m especially excited about leveraging it to modify UI in response to user interaction without JavaScript. Where previously we have used JavaScript to toggle classes or attributes (or to set styles directly), we can now pair :has() selectors with HTML’s native interactive elements.

Supporting a color scheme preference, like “Dark Mode,” is a great use case. We can use a element anywhere that toggles color schemes based on the selected — no JavaScript needed, save for a sprinkle to save the user’s choice, which we’ll get to further in.