How to Invert Color using CSS Filter

Parvez Alam
2 min readDec 1, 2022

--

in this tutorial, we’ll invert color of an HTML element using the CSS. The CSS allows you to invert the color of an HTML element by using the invert() CSS function that you can pass to the filter property.

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

The invert() function accepts a decimal or percentage number value (from 0 to 1 and 0% to 100%)

filter: invert(50%); | invert(0.5);

An illustration of how to completely invert a text’s color is as follows:

<style> .invert { background-color: white; filter: invert(100%); } </style>

How To Use invert class in a Web Page

<p class="invert">Hello! invert color!</p>

As we know, The default color of the text is black, the color is inverted into white when we applied invert(100%).

We have added background-color:white in the CSS class rule so that we can see the result of the color inversion.

Output:

Invert Both colors: background and text color

The invert filter will invert both the background color and the color of an element. The background color won’t be inverted, though, if you only apply the color attribute to the element.

Here’s another example where the color red is inverted to aqua:

<style> .invert { background-color: white; color: red; filter: invert(100%); } </style> <p class="invert">Hello there!</p>

Output:

How To Invert Color in a table

The invert filter can also be applied to other HTML elements, including a table, an image, and a video.

<style> .invert { filter: invert(100%); } </style> <table class="invert" style="background-color: aliceblue;"> <thead> <tr> <td>Field name</td> <td>Mandatory</td> <td>Allowed values</td> </tr> </thead> <tbody> <tr> <td>Seconds </td><td> Yes </td><td> 0-59</td></tr> <tr><td>Minutes </td><td> Yes </td><td> 0-59 </td></tr> <tr><td>Hours </td><td> Yes </td><td> 0-23 </td></tr> <tr><td>Day of month </td><td> Yes </td><td> 1-31 </td></tr> <tr><td>Month </td><td> Yes </td><td> 1-12 or JAN-DEC</td></tr> <tr><td>Day of week </td><td> Yes </td><td> | 0-6 or SUN-SAT </td> </tr> </tbody> </table>

Output:

Conclusion:

In this post, we learned how to invert the colors of an element using CSS. we have used the filter property and set it to invert with a percentage value.

Originally published at https://www.js-tutorials.com on December 1, 2022.

--

--

Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/