Visibility of WordPress blocks for “prefers-color-scheme”

I’m a big fan of dark mode websites, therefore my interest was peaked when I received a question from Michael on how to make WordPress blocks appear conditionally using the browser requested color scheme. Most modern browsers already support the new CSS selector @media prefer-color-scheme. Let’s jump in!

Show/hide content using prefers-color-scheme using CSS

I’m going to show you how to manually use CSS classes inside the WordPress block editor to change content for light or dark mode websites. It’s actually quite simple with a few steps!

1. Create the the CSS classes

Firstly I’m going to create two CSS classes.

  • .light-mode-only
  • .dark-mode-only

Each class will be responsible for hiding the content using display: none while the opposite color mode is enabled. You can copy the CSS snippet.

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

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

Now copy the CSS snippet and we’ll paste it into the custom CSS area of the WordPress Customizer.

Example CSS in the WordPress Customizer
WordPress Customizer

2. Apply the classes to WordPress Blocks

Let’s head into the WordPress Editor and select the block that we want to display on light or dark mode. Click on the block and you’ll see the settings sidebar on the right-hand side. Click the Advanced tabs and you’ll find the “Additional CSS Classes” text box. I’ll add our light-mode-only class here. This means the block will only be visible when the browser is requesting the light color scheme of our website.

Applying light or dark mode to WordPress blocks.

Demo

As a demonstration, I’ve created 2 Group Blocks. I prefer using Group blocks because it’s easier to manage. If your browser prefers dark mode, you’ll see the dark mode block. Keep in mind our website doesn’t support dark mode yet, so the only thing that will change is the blocks below.

Light mode Example Group

This is a group block displayed for light mode only.

Dark mode Example Group

This is a group block displayed for dark mode only.

Want prefered color scheme using our plugin?

I’d love to hear from you if you’d like the color scheme to feature built-in Conditional Blocks. It would be a simple feature that allows you to change the visibility of the WordPress blocks with a few clicks for dark and light mode.

We prioritize features with frequent demand. Send me a message to let me know you’re interested!

Morgan
Morgan