Skip to content

How to invert colors using CSS

New Course Coming Soon:

Get Really Good at Git

How to invert colors of elements and images using CSS

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%);
  }
}

It’s not 100% accurate in my case, because my dark background color is not perfectly black, but it’s better than nothing.

To make things perfect you could also add the image using a CSS background image instead of an img tag in HTML, and I could easily swap that in dark mode.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my CSS Handbook
→ Read my CSS Tutorial on The Valley of Code

Here is how can I help you: