Jaime López
Data Product Developer
Centereach, NY

Sections:

Profiles:

Automatic light/dark theme with CSS

Nowadays, it is expected that web pages change automatically between a light and a dark theme based on the user's desktop theme. Therefore, we, as developers, should provide at least two basic color configurations, a default light set and another for a dark theme.

One way to accomplish that expectation is by setting the style sheet with variables to define the basic colors used in the web page, and a media selector to detect the user's default desktop theme. Below, an example of implementing this solution is shown.

Color variables for the light theme:

:root {
    --body-bgcolor: white;
    --body-fgcolor: #333;
    --link-color: #4169E1;
}

Alternate color variables for the dark theme:

This ones are defined inside a media selector.

@media (prefers-color-scheme: dark) {
    :root {
        --body-bgcolor: #111;
        --body-fgcolor: #ccc;
        --link-color: #B0E0E6;
    }
}

Using variable definitions in element and class selectors:

body {
    background-color: var(--body-bgcolor);
    color: var(--body-fgcolor);
}

a { 
    color: var(--link-color); 
}

input {
    background-color: var(--body-bgcolor);
    color: var(--body-fgcolor);
}

In the previous example, the light color set has three variables: for the background, the text color, and the link color. The media selector uses the feature prefers-color-scheme to detect if the user is using a dark theme. If that is the case, variables are redefined. Finally, element and class selectors are configured using these variables.

Resource:


Date: Feb. 01, 2024