Member-only story
How to Implement a Dark Mode Switch in Your Web Apps
Add color scheme responsiveness to your web app
Dark mode (aka a light-on-dark color scheme) has become very popular in the past few years. It’s arguably easier on the eyes and battery and it’s supported by all major operating systems for desktop and mobile devices.
In this article, I’ll show you how you can make your web application responsive to the color scheme chosen by the user at the operating system level as well as adding a color scheme switch that remembers the user’s choice by saving it in the browser’s local storage.
Table of Contents
· prefers-color-scheme
∘ Pro-tip
· Dark mode switch
· Remembering user’s choice
· Further Reading
prefers-color-scheme
Just as we use CSS media queries to make our web applications responsive to screen resolutions, so we can also use media queries to add responsiveness to the user’s preferred color scheme.
body {
background: white; color: black;
}@media (prefers-color-scheme: light) {
body {
background: white; color: black;
}
}@media (prefers-color-scheme: dark) {
body {
background: black; color: white;
}
}