Keep color in darkmode

(the examples below use tailwind CSS classes)

The problem

When using darkmode it is easy to setup a general rule of how coloring should be in darkmode. Here is an example code:

@media (prefers-color-scheme: dark ) {

  h1, h2, h3, h4, h5, h6 {
    color: #fff;
  }

  p {
    color: #eee;
  }
}

This can be expanded to handle all elements in your HTML.

But sometimes you have sections of your HTML that has another background-color.

Example:

<body>
  <section class="bg-yellow text-white">
    <h1>
      Hi! I am a white heading with a yellow background (in darkmode). 
    </h1>
  </section>
</body>

In the example above the dark-mode CSS will mess it up and the white text will be hard to see with a yellow background.

Solution 1: Use dark:text-black

Use the dark:text-black to ensure that the h1 stays black. Depending on your CSS structure it might not have precedence on the color, if it is part of the section. And thus all individual heading and paragraphs will need to have thex dark:text-black. This works in small cases. But as soon as you have many elements this will be tedious and it’s easy to forget to add it everywhere.

Solution 2: .keep-color

Use a .keep-color class in the section declaration, and generalize it so that the darkmode CSS doesn’t affect sections within a element with .keep-color class.

Example:

@media (prefers-color-scheme: dark ) {

  h1:not(.keep-color *),
  h2:not(.keep-color *),
  h3:not(.keep-color *),
  h4:not(.keep-color *),
  h5:not(.keep-color *),
  h6:not(.keep-color *) {
    color: #fff;
  }

  p:not(.keep-color *) {
    color: #eee;
  }
}
<body>
  <section class="bg-yellow text-white keep-color">
    <h1>
      Hi! I am a black heading with a yellow background (in darkmode).
    </h1>
  </section>
</body>

Result

By using solution two we can target the darkmode specific coloring to all parts NOT wrapped in a .keep-color element. This is done by utilizing the :not() selector.

Might not be performant, but I’m not good enough in CSS to assess that. 🤷 If you have insights about it please do share!