🇨🇿 cs

Dark mode using CSS quick and easy way

With the rise of OLED technology on smartphones and more recently on laptops, finally it’s suitable to switch the view to the so-called dark mode. Someone likes it, someone (like we poor ones with astigmatism) doesn’t. But the web site is displayed as its author intended to, so with custom (and bright) color scheme, it’s easy getting your eyes literaly hurt.

Using modern CSS features it’s easy to create a quick dark mode alternative.

Imagine having following CSS on your site:

body {
    background-color: white;
    color: black;
}

If the website consists mostly of the text to read, it glows unnecessarily on a device with dark mode enabled. Fortunately, modern browsers offer the option to tell what scheme the user prefers. So we can add an inverse option:

@media (prefers-color-scheme: dark) {
    body {
        background-color: black;
        color: white;
    }
}

It can also be done the opposite way. If your site is dark by default, you can add a light variant and ask for light in the media query.

This can be tested in a browser without OS support. In Firefox you need to have developer tools opened. There are buttons with sun and moon icons in the top right corner. I guess their meaning is clear.

Developer tools in Firefox

If you’re using more colors and in more sections, the solution this way would be quite more complicated.

Fortunately, we have CSS variables:

:root {
  --color-background: white;
  --color-content-text: black;
  --color-heading: darkgreen;
}

@media (prefers-color-scheme: dark) {
    :root {
        --color-background: black;
        --color-content-text: white;
        --color-heading: lime;
    }
}

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

h1 {
    color: var(--color-heading);
}

This way we can query variables anywhere in the entire CSS file and have colors defined in only one place.

P.S. My site supports dark mode, you can try it ;-)

Comments