I want to provide a "dark mode" switch on a website. That would be easy by using some CSS.
But then: Modern browsers can already tell the website that they want to use a dark mode (prefers-color-scheme
). And I can also react to that via CSS.
@media (prefers-color-scheme: dark) {
html {
filter: grayscale(0.75) invert(1) contrast(1);
}
}
My problem is: I do not want these mechanisms (button on the website and browser preference) to collide. And I need the button on the website, because many users don’t know that their browser can change the preference.
Is there any mechanism that would allow a website to provide a button that would change the browser preference?
I fully understand that you would usually not want to allow websites to do something like "change my preferences", however, it seems like a good idea regarding the prefers-color-scheme
.
2
Answers
This is a great reference on implementing a dark mode switch.
The concept is that you:
provide a mode switch which operates within the website, and persist the value of the switch in session storage or local storage so that the mode stays the same as the user browses from page to page;
listen for any changes to the OS dark mode setting and adjust the local setting to match;
if there is no mode in session storage or local storage, such as would happen when a user visits the site for the first time, then read the OS dark mode setting and use that as the initial setting.
I prefer a three-way choice for the user:
Changes to the browser/OS setting are then ignored if the user has explicitly chosen light or dark mode.