Ronalds Vilciņš

Invert Colours With One CSS Filter

CSS can invert an element’s colours with one declaration:

.invert {
  filter: invert(100%);
}

Apply the class to any element that needs the effect:

<div class="invert">This element's colours will be inverted.</div>

invert(100%) maps each colour to its opposite. Black becomes white, white becomes black, and images inside the element are inverted too. That last part makes this a visual effect rather than a reliable way to build dark mode.

Inverting the whole page

The filter can be applied to body if you really want everything on the page to change:

body {
  filter: invert(100%);
}

This also affects photographs, videos, shadows, and brand colours. Technically it works, but I would not use it as a substitute for choosing proper theme colours.

The function accepts values from 0% to 100%:

.invert {
  filter: invert(50%);
}

At 50%, colours move towards neutral grey. It is not a gentler full inversion, which is an easy detail to miss.

Fallbacks for older browsers

When this article was written, older browser support could be handled with @supports:

@supports (filter: invert(100%)) {
  .invert {
    filter: invert(100%);
  }
}

Older Safari versions used the prefixed property:

.invert {
  -webkit-filter: invert(100%);
  filter: invert(100%);
}

For a deliberate visual treatment, invert() is pleasantly small. For interface themes, use explicit colours and leave the photos alone.

Enjoyed reading this?

If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.

← Back to all articles