Categories
JavaScript Answers

How to Invert the Colors of an Image in CSS or JavaScript?

Spread the love

To invert the colors of an image in CSS, we can use the filter CSS property.

To invert the colors of an image in JavaScript, we can set the style.filter property of the element to the same value.

For instance, we can write:

<img src="https://picsum.photos/200/300">

to add an image.

Then we can invert the colors of the image with the following CSS:

img {  
  -webkit-filter: invert(1);  
  filter: invert(1);  
}

We just set the -webkit-filter and filter properties to invert(1) to invert the colors of the image.

To do the same thing with JavaScript, we write:

document.querySelector("img").style.filter = "invert(1)";

Conclusion

To invert the colors of an image in CSS, we can use the filter CSS property.

To invert the colors of an image in JavaScript, we can set the style.filter property of the element to the same value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *