Selectively show and hide parts of your webpage based on dark mode

Recently I set up getpersonalbest.com as a dedicated website for my workout-tracking app Personal Best. Like this website, it supports dark mode.

As well as the website’s appearance changing in dark mode, the screenshots on the home page also change depending on whether or not dark mode is enabled.

To do this, I created a couple of utility classes in my CSS:

@media (prefers-color-scheme: dark) {
  .light-mode-only {
    display: none;
  }
}
@media (prefers-color-scheme: light) {
  .dark-mode-only {
    display: none;
  }
}

Using them in your HTML is straightforward:

<img class="light-mode-only" src="light-mode-screenshots.png" />
<img class="dark-mode-only" src="dark-mode-screenshots.png" />

And that’s it! Now I can easily hide and show parts of my website based on the user’s dark mode setting.

It works on this website too – the paragraph below will change based on your device setting. Try turning dark mode on and off and you’ll see the text change automatically.

Light mode is enabled.

Dark mode is enabled.

Thanks for reading.

To get in touch, email me or find me on Mastodon or Twitter.

If you liked this post, you'll love my iOS apps. Check them out below.

Personal Best

Level up your workouts

Taylor's Version

Upgrade Taylor Swift songs in your playlists

SalaryPig

Meet Trevor, the salary-tracking pig

Taylor Swift Quiz

How well do you know Taylor Swift?

Football Quiz

Test your soccer knowledge