How to add Dark theme to your website using HTML CSS JavaScript? (Short Answer)
Photo by Ash Edmonds on Unsplash
To create dark theme you need first to create HTML toggle element (usually <button>
element), second to create CSS variables to be used by both themes (light and dark), and third create event listener to add and remove class name from HTML element. 👉 A real example.
In HTML file:
Use <button>
element to toggle themes. This will be use to switch from a theme to another.
<button class="toggle">
start mode
</button>
<h1>
Theme Switch
</h1>
In CSS file:
As first step you need to style CSS variables inside :root
and this is will be your default theme which is light.
Second step, use same variables with different colors (values) inside html.dark
for your dark theme, you can use different name rather than dark if you want.
The third step, use CSS transition to change property values smoothly, over a given duration. This is optional.
Final step use these variables to style your HTML elements.
/* Step 3 - This is to transfer from one theme to another smoothly */
* {
transition: all 0.5s ease-in;
}
/* Step 1 - This will be your default theme (light) - select and style
CSS variables */
:root {
--primary-color: white;
--secondary-color: darkblue;
}
/* Step 2 - This will be your dark theme - select and style elements
using CSS variables */
html.dark {
--primary-color: black;
--secondary-color: lightblue;
}
/* Step 4 - Use these variables */
body {
background-color: var(--primary-color);
color: var(--secondary-color);
}
In JavaScript file:
At first return the .toggle
element using the document method querySelector()
.
Secondly, use addEventListener()
method, "click"
event, and a function to add/ remove "dark"
to/ from html
class list.
const toggle = document.querySelector(".toggle")
// switch theme (Dark/ Light)
toggle.addEventListener("click", (e) => {
const html = document.querySelector("html")
if (html.classList.contains("dark")) {
html.classList.remove("dark")
e.target.innerHTML = "Dark Mode"
} else {
html.classList.add("dark")
e.target.innerHTML = "Light Mode"
}
})