How to invert colors using CSS
By Flavio Copes
Learn how to invert the colors of an element or image in CSS with filter: invert(100%), handy inside a prefers-color-scheme: dark query for dark mode.
You can invert the colors of any element in CSS using the filter property with the invert() function:
filter: invert(100%);
At 100% every color flips to its opposite. Black becomes white, white becomes black, and every color in between gets swapped too.
You can also write invert(1), which is the same as invert(100%). A value of 0 leaves the element untouched, and anything in between applies a partial inversion.
Why I needed this
I had this problem. I added a “black on white” image on a page, only to realize that with dark mode, my page correctly changes the background to black, but the image remains white on black.
Kind of bad.
So I added this rule to my CSS to detect dark mode and automatically invert the color of the image:
@media (prefers-color-scheme: dark) {
.my-image {
filter: invert(100%);
}
}
The prefers-color-scheme: dark media query matches when the user has dark mode enabled at the operating system level. Inside it, the filter flips the image, so black lines on white become white lines on black.
It’s not 100% accurate in my case, because my dark background color is not perfectly black, but it’s better than nothing.
Inverting the whole page
You can apply the same filter to the html element to get a quick and dirty dark mode:
html {
filter: invert(1) hue-rotate(180deg);
}
The hue-rotate(180deg) part is there because invert() also flips hues. A blue link would turn orange. Rotating the hue by 180 degrees brings colors back close to their original tone, while keeping light backgrounds dark.
The photo problem
Be careful with photos. Inverting the whole page also inverts every image, and a photo of a person ends up looking like a film negative.
The fix is to invert images a second time, which cancels the effect:
img {
filter: invert(1) hue-rotate(180deg);
}
To make things perfect you could also add the image using a CSS background image instead of an img tag in HTML, and swap it with a different one in dark mode.
Related posts about css: