User Prefers Dark Mode/Light Mode

jdbrewerhofmann

JD Brewer-Hofmann

Posted on March 30, 2021

User Prefers Dark Mode/Light Mode

This blog covers super basic theming in CSS based on the user's preferences for light mode or dark mode.

CSS variables

If you are unfamiliar with CSS variables, this doubles as an introduction. CSS variables are declared at the top level of our document like so

:root {
  --black: #101010;
  --white: #ffffff;
  --brand: #ff9999;
}
Enter fullscreen mode Exit fullscreen mode

Then we can call the variables for our H1 tag like so

h1 {
  background: var(--white);
  color: var(--black);
}
Enter fullscreen mode Exit fullscreen mode

Using User Preference and Variables to update our page

Let's start with one element and toggle between dark mode and light mode. Utilizing user preference queries, we can check to see if our user prefers dark mode or light mode. Together with our CSS variables our CSS file will read as

:root {
  --black: #101010;
  --white: #ffffff;
  --brand: #ff9999;
}
h1 {
  background: var(--white);
  color: var(--black);
  padding: 5vh 0;
  text-align: center;
  transition: 1s;
}
@media (prefers-color-scheme: dark) {
  h1 {
    background: var(--black);
    color: var(--white);
  }
} 
Enter fullscreen mode Exit fullscreen mode

one

By adding in a few lines of CSS, our H1 will update when the user changes their preferences. That is super responsive.

Extending Into a Whole Theme

Taking the concepts another step, we can refactor our code to change the variables themselves to change if our user prefers dark mode. Then we can use the same CSS variables regardless of user preference.

:root {
  --background: #ffffff;
  --text: #101010;
  --brand: #ff9999;
}
@media (prefers-color-scheme: dark) {
  :root {
    --background: #101010;
    --text: #ffffff;
  }
}
body {
  background: var(--background);
  color: var(--text);
}
h1 {
  border: 2px solid var(--brand);
  padding: 5vh 0;
  text-align: center;
  transition: 1s;
}
Enter fullscreen mode Exit fullscreen mode

two

It's basic, but the concept works well, and with little code. If I dig into this further I would work to integrate the brand color in an accessible way beyond a border color.

💖 💪 🙅 🚩
jdbrewerhofmann
JD Brewer-Hofmann

Posted on March 30, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related