DEV Community

Cover image for A quick way to add Dark Mode for any site
Mikita Chyzhyk
Mikita Chyzhyk

Posted on

A quick way to add Dark Mode for any site

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();
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)