A quick way to add Dark Mode for any site
Mikita Chyzhyk
Posted on June 8, 2021
For those who don't want to bother and write styles for Dark Mode, I suggest this simple solution using CSS filters.
It may not be the best way, but for many sites it will still look pretty good.
const darkCss = `
@media screen {
/* Leading rule */
html {
-webkit-filter: invert(100%) hue-rotate(180deg) brightness(80%) contrast(70%) grayscale(40%) !important;
filter: invert(100%) hue-rotate(180deg) brightness(80%) contrast(70%) grayscale(40%) !important;
}
/* Reverse rule */
img,
video,
:not(object):not(body)>embed,
object,
svg image,
[style*="background:url"],
[style*="background-image:url"],
[style*="background: url"],
[style*="background-image: url"] {
-webkit-filter: invert(100%) hue-rotate(180deg) !important;
filter: invert(100%) hue-rotate(180deg) !important;
}
[style*="background:url"] *,
[style*="background-image:url"] *,
[style*="background: url"] *,
[style*="background-image: url"] *,
input,
[background] * {
-webkit-filter: none !important;
filter: none !important;
}
/* Text contrast */
html {
text-shadow: 0 0 0 !important;
}
/* Full screen */
:-webkit-full-screen, :-webkit-full-screen * {
-webkit-filter: none !important;
filter: none !important;
}
:-moz-full-screen, :-moz-full-screen * {
-webkit-filter: none !important;
filter: none !important;
}
:fullscreen, :fullscreen * {
-webkit-filter: none !important;
filter: none !important;
}
/* Page background */
html {
background: rgb(181,181,181) !important;
}
}
`;
checkTheme();
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
checkTheme();
});
function checkTheme() {
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
switchTheme(true);
} else {
switchTheme(false);
}
}
function switchTheme(dark = false) {
if (dark) {
document.head.insertAdjacentHTML('beforeend', `<style id="darkStyle">${darkCss}</style>`);
} else {
document.getElementById('darkStyle') && document.getElementById('darkStyle').remove();
}
}
💖 💪 🙅 🚩
Mikita Chyzhyk
Posted on June 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webcomponents Decorator @define: O Feitiço supremo para turbinar seus Custom Elements!
October 31, 2024
webcomponents Custom Elements Unleashed: Dominando customElements.define() e .get() como um Jedi do Front-end!
October 30, 2024