Easiest way to do a dark theme with CSS vars (and JS!)
Corentin
Posted on March 10, 2020
1. Set up your HTML
<body>
<div class="container">
<h1>My beautiful theme</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
Repellat nihil nisi quidem pariatur optio iste vero id velit deleniti tenetur, sit deserunt.
</p>
<button id="theme-switcher">Switch theme!</button>
</div>
</body>
We will use a simple button so that our users can change the theme.
2. Set up your CSS, using vars
:root {
--background: #f7fafc;
--container: #edf2f7;
--text-primary: #1a202c;
}
.dark {
--background: #4a5568;
--container: #2d3748;
--text-primary: #f7fafc;
}
body {
background-color: var(--background);
font-family: sans-serif;
color: var(--text-primary);
}
.container {
background-color: var(--container);
padding: 10px;
text-align: center;
}
The :root
variables will be those used by default when the page loads, and .dark'
matches the dark theme.
NB: You can define as many themes as you want
Now, if you apply the class "dark" to the body:
3. Set up the "switch theme" button
const themeSwitcher = document.getElementById('theme-switcher');
themeSwitcher.addEventListener('click', function() {
document.body.classList.toggle('dark');
})
We simply add an event listener on the button to change the theme on click! Now, if you click on the button, it works!
4. Save the user's choice in localStorage
First, add this line on the eventListener:
localStorage.setItem('theme', document.body.classList);
When the user changes the theme, we save it into localStorage.
Then, at the top of the script:
if(localStorage.getItem('theme') === "dark") {
document.body.classList.toggle(localStorage.getItem('theme'));
}
Now, as soon as the user visits your site, the theme he has chosen will be automatically applied!
You can find the code here: https://jsfiddle.net/03h84v6m/1/
🦄
Posted on March 10, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.