Implement Dark Mode with Custom Properties and the prefers-color-scheme
Media Feature
— #css
The easiest way to implement OS-level Appearance styling is by configuring background and foreground swatches in :root
alongside a colour palette, and defining a (prefers-color-scheme: dark)
media query that adjusts these swatches when true:
:root {
--background: #fff;
--foreground: #000;
@media (prefers-color-scheme: dark) {
--background: #000;
--foreground: #fff;
}
}
Of course, you don’t need to use pure white and black and, in practice, it would be preferable to establish the colours as variables or Custom Properties prior, but these are the only requirements to adjust the Appearance to Light or Dark with the operating system.
Changing the accent or entire palette to values that are well-optimised for the current Appearance is as easy as establishing those values at :root
and redefining them within the media query too. For example, Apple's default system colours change slightly between Light and Dark Appearance:
:root {
--red: #ff3b30;
--orange: #ff9500;
--yellow: #fc0;
--green: #34c759;
--cyan: #00c7be;
--blue: #007aff;
--purple: #af52de;
--magenta: #ea4c89;
@media (prefers-color-scheme: dark) {
--red: #ff453a;
--orange: #ff9f0a;
--yellow: #ffd60a;
--green: #30d158;
--cyan: #66d4cf;
--blue: #0a84ff;
--purple: #bf5af2;
--magenta: #ff5295;
}
}