paint-brush
Adding Dark Mode to Your Website Using a Single Line of HTMLby@kumaram
5,491 reads
5,491 reads

Adding Dark Mode to Your Website Using a Single Line of HTML

by Shubham KumaramJuly 10th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<meta name="color-scheme" content="dark light">
featured image - Adding Dark Mode to Your Website Using a Single Line of HTML
Shubham Kumaram HackerNoon profile picture

This weekend, I wanted to explore how I can add dark mode to my website, for the benefit of the ~2 people who read my blog. I decided to keep it simple, and use the system-wide preference for the colour mode. I thought I might have to use arcane CSS and Javascript incantations to first query the system dark mode preference, and then set the colours accordingly, but the browser vendors have made it so much simpler and easy to use.

Enough Talk! Show me the code

Here's all the code required to add dark mode to any website (with a few caveats I'll explain later in this post):


<meta name="color-scheme" content="dark light">


That's it! It requires no custom CSS, and is supported in all modern browsers. There's also a corresponding CSS property: color-scheme, which works on individual tags.


There's a major caveat though. If you've set custom colours anywhere in your page, using the color or background CSS properties, this won't work for you. It'll invert the colours only for elements which have no explicit colour set.

Other approaches

If you make substantial use of custom colours in your web pages, you can use the prefers-color-scheme media query in your CSS to get a more fine-grained control on how your webpage looks in different modes.


Here's an example:

@media (prefers-color-scheme: dark) {
  body {
    background-color: black;
    color: white;
  }
}


I hope this helps!


Also published here.