Dark mode can be implemented with a single line of code. Let’s see how it's done and the benefits and drawbacks of this simple approach.
filter: invert(1) #
invert() function as the value of the filter property will take the number from 0 to 1 or percentages from 0% to 100% to invert the colors of the element and its children. Applying filter: invert(1) or filter: invert(100%) results in fully inverted colors.
To invert the colors of the entire website, you need to apply filter: invert(1) on the highest-level element.
html[data-theme='dark'] {
filter: invert(1) hue-rotate(180deg);
}
To switch the theme, you need a toggle button and a class with dark mode styles to be toggled on the button click. Check the my Demo link Codepen example below and click the button in the middle to change the color scheme:
<img src="sun.svg"
data-light-src="sun.svg"
data-dark-src="moon.svg"
data-activate-theme="light"
alt="light theme"
id="theme-selector"
class="icon"
onclick="switchTheme(this)">
We must employ some basic JavaScript by targeting the toggleTheme = (theme) inside the listener function. Then we can toggle the dark mode class on the top of hierarchy to apply the filter: invert(1) sitewide.
const html = document.getElementsByTagName('html')[0];
const toggleTheme = (theme) => {
html.dataset.theme = theme;
}
if (localStorage.getItem('theme')) {
toggleTheme(localStorage.getItem('theme'));
} else if (window.matchMedia('(prefers-color-scheme)').matches) {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
toggleTheme('dark');
} else if (window.matchMedia("(prefers-color-scheme: light)")) {
toggleTheme('light');
}
window.matchMedia("(prefers-color-scheme: dark)").addListener(
e => {
if(e.matches) {
toggleTheme('dark');
setupThemeIcon();
}
}
);
window.matchMedia("(prefers-color-scheme: light)").addListener(
e => {
if(e.matches) {
toggleTheme('light');
setupThemeIcon();
}
}
);
}
function switchTheme (themeElement) {
if (themeElement) {
toggleTheme(themeElement.dataset.activateTheme);
localStorage.setItem('theme', themeElement.dataset.activateTheme);
}
setupThemeIcon();
}
function setupThemeIcon () {
const themeElement = document.getElementById('theme-selector');
if (html.dataset.theme === 'light') {
themeElement.src = themeElement.dataset.darkSrc;
themeElement.dataset.activateTheme = 'dark';
} else if (html.dataset.theme === 'dark') {
themeElement.src = themeElement.dataset.lightSrc;
themeElement.dataset.activateTheme = 'light';
}
}
Here’s demo Dark mode
🐘 There we have our Dark mode implemented. Great job guys!,
If you enjoyed this article, you may also like Dervic Blog's.
Comments (0)