Dark mode seems to be here to stay.

Initially, it was mainly used by developers in their code editors.

Now, its all over the place: mobile, desktops, and now even the web.

A better approach to implementing dark mode on your website

Supporting dark mode is turning from a niche to a must-have.

Of course, it depends on your niche.

When it comes to dark mode for websites there are multiple approaches.

Article image

Lets get started with the first option.

Joke aside, it consists of one line of CSS.

It’s free, every week, in your inbox.

Article image

As can be seen in the example it works really well, but with an issue: it alsoinvertsimages.

This happens because the filter property additionally applies to images, background, and borders.

But everything transitions so abruptly.

Article image

Now, it wont always look great.

To name a variable we need to prepend–to the variable name.

And to use it, we make use of the functionvar().

Article image

Now lets go back to our scenario and attempt to implement dark mode this way.

Its much more cumbersome.

Otherwise, it wont work.

Article image

Theme toggle logic

Lets now work on the JS that makes the switch possible.

It is actually, again, very simple:

So, what did we do so far?

The way the theme works is by applying a data attribute over the HTML element.

Article image

For that, we will use thelocalStorageAPI.

Sign up for updates on everything related to programming, AI, and computer science in general.

Also tagged with

Article image

Article image