More and more websites now offer the ability to theme switcher. In order to meet the needs of users, or to highlight their own characteristics, so provide personalized customization functions.
But how to quickly achieve the theme switcher? This article will show you how to achieve theme switcher using CSS.
css varโ
Declare a variable. The property name starts with --
, and the property value can be any valid CSS value.
div {
--main-bg-color: grey;
}
A selector is the visible scope of a specified variable that is only used to match the current selector and its descendants. A general best practice is to define it under the root pseudo-class :root
so that it can be accessed anywhere in the HTML document.
:root {
--main-bg-color: grey;
}
When using a local variable, enclose the var()
function to represent a valid attribute value:
div {
background-color: var(--main-bg-color);
}
css var fallback valueโ
The var()
function allows you to define multiple fallback values that will be replaced if the given value is undefined.
div {
background-color: var(--main-bg-color, #fff);
}
html dataset attributeโ
Start by defining data-theme
attribute on the root element of the page.
<html lang="en" data-theme="light" />
dark/light theme variable definitionโ
And then we can define the variables for dark and light theme.
:root {
--main-bg-color: #fff;
--main-text-color: #333;
}
:root[data-theme="dark"] {
--main-bg-color: #333;
--main-text-color: #fff;
}
dark/light theme switcher buttonโ
Use javascript to change the html dataset attribute data-theme
to dark
or light
when clicking the button.
const switchThemeBtn = document.querySelector('#switch-theme-btn');
switchThemeBtn.onclick = () => {
const theme = document.documentElement.dataset.theme;
document.documentElement.dataset.theme = theme === 'dark' ? 'light' : 'dark';
}
use theme var in cssโ
Finally we can use the css variables in css.
.container {
background-color: var(--main-bg-color);
}
remember themeโ
When user change the theme, we can remember the theme config in localStorage
and restore it when user reload the page.
const switchThemeBtn = document.querySelector('#switch-theme-btn');
switchThemeBtn.onclick = () => {
const theme = document.documentElement.dataset.theme;
const newTheme = theme === 'dark' ? 'light' : 'dark';
document.documentElement.dataset.theme = newTheme;
localStorage.setItem('theme', newTheme);
}
// set theme when user reload the page
document.addEventListener('DOMContentLoaded', () => {
const theme = localStorage.getItem('theme');
if (theme) {
document.documentElement.dataset.theme = theme || 'light';
}
})
That's all. Enjoy!