Just Frontend Things

Detect and style for Dark Mode in CSS



Using very little CSS it is possible to detect wether the user has dark mode enabled or not. With this unexpectedly way you'll ease your visitors eyes.

Lately almost all devices, phones and desktops, has a way to set the system into dark mode. And a way to please your visitor is to continue with the dark mode on your site as well.

The prefers-color-scheme CSS media feature lets you detect if the user's system is set to dark mode or light mode.

By writing a media query, @media, and using prefers-color-scheme: dark you can style for dark mode.

@media (prefers-color-scheme: dark)

It can also style for a prefered color scheme of light.

@media (prefers-color-scheme: light)

Now let's try to make a background light red in light mode and dark red in dark mode with this code.

.example { color: #000000; background-color: Salmon; } @media (prefers-color-scheme: dark) { .example { color: #FFFFFF; background-color: DarkRed; } }

Which should give us a result like this:

Light mode and dark mode using CSS