CSS

Automating CSS Dark Mode

📣 Sponsor

The most common implementation of dark mode is a button which enables or disables dark mode, based on user preferences. By default then, we can store their preference and keep their dark or light mode enabled while using our website.

Another way to do this, is to automatically change the website to dark mode at a certain time, or perhaps based on their computer's settings. Let's look at how to do that.

Dark Mode Based on Operating System

Setting dark mode based on the operating system's settings is the easiest way to enable dark mode. If the user is using dark mode on their phone, tablet or computer, we can then show our website in dark mode by using the following CSS:

/* Light mode CSS */ body { background: white; } @media (prefers-color-scheme: dark) { /* If the operating system is using dark mode, then apply this CSS */ body { background: black; } }

Now we can have specific styles applied only when the operating system is in dark mode, which is usually automatic for most operating systems. That means dark mode will auto enable at a certain time. This also has pretty broad support:

Data on support for the prefers-color-scheme feature across the major browsers from caniuse.com

Allowing User Override

If you want to allow a user override, then you can add a custom class to the body tag, which you can then target to override dark and light mode styles:

<button id="dark-mode"></button>
document.addEventListener("DOMContentLoaded", function() { document.getElementById("dark-mode").addEventListener("click", function(e) { if(!document.body.classList.contains("dark-mode")) { document.body.classList.add("dark-theme"); } else { document.body.classList.remove("dark-theme"); } }); });

Now, when the user clicks the button dark-mode, we will add a class to the body, which will enable dark mode (based on our CSS).

Enable Dark Mode Based on Time

If you have the need to set dark mode at a certain time every day, we can do that with Javascript. In this example, we will load up the file darkmode.css if the current hour is less than 6am, or more than 7pm.

document.addEventListener("DOMContentLoaded", function() { let time = new Date().getHours(); if(time < 6 || time > 19) { let link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'darkmode.css'; link.media = 'all'; document.head.appendChild(link); } });
Last Updated 1622402001003

More Tips and Tricks for CSS

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email