Add Automatic Dark Mode to Your Website with Just CSS

No Javascript needed

This simple piece of CSS will make your website available in a light or dark scheme based on the user’s device preferences. Automatically. No Javascript required.

@media (prefers-color-scheme: dark) {
  /* Invert all elements on the body while attempting to not alter the hue substantially. */
  html {
    filter: invert(100%) hue-rotate(180deg);
  }

  /* Workarounds and optical adjustments. */

  /* Do not invert media (revert the invert). */
  img, video, iframe {
    filter: invert(100%) hue-rotate(180deg);
  }

  /* Improve contrast on icons. */
  .icon {
    filter: invert(15%) hue-rotate(180deg);
  }

  /* Re-enable code block backgrounds. */
  pre {
    filter: invert(6%);
  }

  /* Improve contrast on list item markers. */
  li::marker {
    color: #666;
  }

  /* A class to exclude elements that are not suitable for changing the color scheme. 
     Do not invert certain elements or images (useful for SVG images or emojis). */
  .no-invert, .no-invert img {
    filter: invert(100%) hue-rotate(180deg);
  }
}

For certain elements such as an SVG image or any other content that you want to exclude from color inversion, add the "no-invert" class to the wrapping element in the HTML or editor.

Example:

<div class="no-invert">
  <img src="assets/fonts/font-awesome/latest/svgs/solid/arrow-up-right-from-square.svg">
</div>

<span class="no-invert">🙂</span>

Emojis are characters – letters and cannot be targeted with CSS without wrapping them. So if you have any user content on your site like comments or chat, additional Javascript is needed.

A note about the WordPress Block editor

It’s best to put this code in your child theme’s CSS stylesheet and not in the “Additional CSS” field in the site editor.

With “Additional CSS” you can see this in real time, but only when you edit the design of your site. Problems occur when using the block editor to edit a page or post. When a “dark web” is detected, WordPress will add an “is-dark-theme” class to the body of the block editor. Then when they try to add CSS their own way, some elements are not visible at all. But it works fine on live site.

Don’t use a child theme? These days, you generally don’t need a child theme for themes that support the site editor. But only until some additional changes are needed. This is one of them. Create a child theme anyway. You can try the Child Theme Configurator plugin in a few clicks, and you have one right away.

Leave a Reply

Your email address will not be published. Required fields are marked *