W3.CSS Dark Mode
Dark Mode
Dark mode uses dark background colors with light text.
With W3.CSS, you can switch between light and dark mode by adding or removing the w3-black class.
Example
<button class="w3-button w3-black" onclick="darkMode()">Toggle Dark Mode</button>
<script>
function darkMode() {
document.body.classList.toggle("w3-black");
}
</script>
How It Works
The document.body property refers to the <body> element.
The classList.toggle() method adds the w3-black class if it is not there, and removes it if it is already there.
This lets the same button switch between light and dark mode.
Dark Mode for a Section
You can also switch dark mode on a single section instead of the whole page.
Example
<div id="demo" class="w3-container">
<h2>Dark Mode Section</h2>
<p>Click the button to change this section.</p>
</div>
<button class="w3-button w3-black" onclick="darkMode()">Toggle Dark Mode</button>
<script>
function darkMode() {
document.getElementById("demo").classList.toggle("w3-black");
}
</script>
What You Have Learned
- Dark mode uses dark backgrounds with light text
- The
w3-blackclass can create a simple dark mode classList.toggle()can switch dark mode on and off- Dark mode can be applied to the whole page or to a single section