Home
Detect if the system prefers dark / light mode
- Aug 23, 2020
- · 1 min read
There exists a CSS media feature called prefers-color-scheme
that lets you detect if the user prefers a dark / light mode on their system.
Turn on Dark Mode (macOS):
on ios and macOS, you can toggle these settings via:
Settings > Appearance
Usage:
Light Mode:
@media (prefers-color-scheme: light) {}
Dark Mode:
@media (prefers-color-scheme: dark) {}
via JavaScript:
function checkDarkMode() {
return (
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
);
}
Example:
<html>
<style>
body {
background: white;
}
h1 {
color: black;
}
@media (prefers-color-scheme: dark) {
body {
background: black;
}
h1 {
color: white;
}
}
</style>
<body>
<h1>prefers-color-scheme</h1>
</body>
</html>