Why this dark mode toogle is working just with the background and not the text?

Viewed 82

I'm building a website with cargo collective and I need a dark mode toggle that switch the background color on click but ever the text color. For the moment is just working with the background and it's not affecting the text.

the toggle i'm using:

**<button onclick="myFunction()">Toggle dark mode</button>
<script>
function myFunction() {
   var element = document.body;
   element.classList.toggle("dark-mode");
}**
</script>

Css I wrote:

body {
    background-color:#d9ff76!important;
}
.dark-mode {
  background-color: black!important; 
    }

I'd like H1 and even all the text to be affected by the dark mode but inside > .dark-mode { I can't write H1 or p or whatever.

This is how cargo define H1:

[data-predefined-style="true"] h1 {
    font-family: "Le Murmure", Icons;
    font-style: normal;
    font-weight: 400;
    padding: 0;
    margin: 0;
    font-size: 45rem;
    line-height: 1.2;
    white-space: nowrap;    
    }

Does anyone knows how to make it work?

2 Answers

One way to do this that would helps you write less CSS code is to to use * selector to make every element inherit the body color. And then if there is a need change for some specific element like so:

function myFunction() {
  var element = document.body;
  element.classList.toggle("dark-mode");
}
*, *:after, *:before {
  color: inherit;
}
body {
  background-color: #d9ff76;
}
.dark-mode {
  background-color: black;
  color: white;
}

.dark-mode button {
  color: black;
}
<button onclick="myFunction()">Toggle dark mode</button>
<h1>I'm a h1</h1>
<p>I'm a p</p>

You can determine what the color of elements is going to be, if the class of body was some specific class. For example, if you wanted your h1 to be white, you can simply use the selector I did at the bottom.
Surely read this article about dark mode via Css Tricks.

const btn = document.querySelector('button');
const el = document.querySelector('.el');

btn.addEventListener('click', () => {
  el.classList.toggle('dark');
})
.el {
  width: 400px;
  height: 300px;
  border: 1px solid black;
}

.dark {
  background-color: #121212
}

/* Important */
.dark h1 {
  color: #f0f0f0
}
<button type="button">Toggle</button>
<div class="el">
  <h1>Hi</h1>
</div>

Related