Website Dark/Light Mode

CSS specifications are constantly changing so CSS is constantly getting new functionalities. One of them is media query for dark mode: prefers-color-scheme: light/dark. Dark mode is gaining popularity as is it supposed to cause less harm to eyes, makes nighttime reading easire and prolonges battery life of some devices.

If we want to use dark mode, we can use the following media query.

@media (prefers-color-scheme: dark)

This changes the color of the background, fonts and other elements, so they are consistent with the dark theme. If we wish to use light mode, we need to use the following media query:

@media (prefers-color-scheme: light)

When using this type of formatting, we should create 2 color themes, one for each mode, which is simple when creating smaller sites, but gets complicated on bigger projects, especially when you take into consideration future changes. Any changes to any element would have to be changed for for both modes.

A simpler method would be to use a CSS filter and flip all colors to their opposites:

@media (prefers-color-scheme: dark) {
    html {
        filter: invert(100%);
    }
}

The problem with this approach is that it really flips all colors, including shades and colors, that shouldn’t be changed, for example colors of pictures. This approach is therefore suitable only on smaller sites that contain text.

The best way therefore is to use variables. In CSS variables need to be defined first:

:root {
    --color-background: #fff;
    --color-text: #212121;
}

They are then used in the following manner:

body {
    background-color: var(--color-background);
    color: var(--color-text);
}

After that, we need to define the variables again for dark mode:

@media (prefers-color-scheme: dark) {
    :root {
        --color-background: #212121;
        --color-text: #ededed;
    }
}

This way, we can control all colors and if we decide to change a color in the future, we can do it in one spot, avoiding having to change each element individually.

Even though this functionallity has been added to CSS, it doesn’t mean it is available everywhere. This depends on the browser. At the moment, the media query for dark mode works only on the latest updates for Firefox, Chrome and Safari and is expected to come to Edge and other browsers soon.

Leave a Reply

Your email address will not be published. Required fields are marked *