Introduction

Dark themed websites are on a really popular trend lately.Beside aesthetics, the Dark Mode meets some needs too: visual comfort, battery usage...There are several ways to implement a Dark Mode.Today, we are going to review a rather simple one: it fits in one CSS line.

The CSS property "filter"The CSS property filter allows us to apply a filter on a DOM element (blur, opacity, grayscale...). We can for instance use it to adjust the rendering of an image or a background.

Among its possible values, we find invert(). invert() takes a number between 0 and 1 (or between 0% and 100%) as parameter, and inverts the colors of an element and its children. A value of 100% means a complete inversion of the element colors.

So, in order to invert the colors of an entire web page, we only have to apply filter: invert(1) on the highest level of the DOM::root { filter: invert(1); }

Before / after



Other colors adjustments

All colors are now inverted, which can be a problem: if there are images, or some buttons that should stay as defined, they are also inverted.

Here are the two steps to solve this issue: 

Step 1In addition to invert(1), we apply hue-rotate(180deg) to preserve initial colors::root { filter: invert(1) hue-rotate(180deg); }

Before / after (blue stays blue)

Step 2We apply the same property on elements that must stay unchanged, like images, or navigation bar. In order to do this, we implement a class name "inverted", which we will use on the elements that we want..inverted {  filter: invert(1) hue-rotate(180deg); }

Before / after


Live example

I illustrated this method with a on/off button on codepen:https://codepen.io/estellepicq/pen/WNNMpqp

Pros and cons

Pros: Cannot be simpler! As long as we use it on a really basic website (uncomplicated DOM, monochromatic...)Cons: As soon as the website become more complicated, with many images and colors, that method will be not so simple, because we will have to invert the element one by one. This approach does not seem very sustainable.

ConclusionAs mentioned at the beginning of this post, other methods exist. I prefer using a CSS variables system to build different themes (light, dark, different colors...).I will detail this system in a future post. You can already see a live example on my personal website.



Sources :https://dev.to/ekaterina_vu/dark-mode-with-one-line-of-code-4lkmhttps://www.youtube.com/watch?v=qimopjP6YoM&list=WL&index=5&t=1s