Change Images to Black and White with CSS
If you’ve ever needed to handle changing some colors on an object on a web page, I think the default position would be to edit the item in Photoshop and then add it in via an Image tag. For images, that still might be the right move but here is a way to change items from color to black and white in CSS.
The Saturate filter function allows you to saturate or de-saturate an image with one line of CSS. In your CSS, target the item and declare filter: saturate(x). X will be a numerical value. 0 for completely de-saturated, 1 for the default value. You can go beyond 1 to get some really crazy results but I’m not sure what that use case would be.
One use case I could think for this is let’s say you have a UI where a user is selecting from a number of options. Something like Netflix wouldn’t really work because you don’t want to mess with Movie posters but that is the type of behavior we are considering. As a visual indicator, on hover (or on click), you can apply that filter function so the user has a visual note on what they are choosing. In the example below, I just used emojis but this would work with images too.
I have done some tweaks to make it look nicer but here are the most important lines.
.container > p {
filter: saturate(0);
}
.container > p:hover {
filter: saturate(1);
cursor: pointer;
}
By default, make the emojis have 0 saturation (so black and white), and then on hover turn that saturation to 1, so the individual emoji appears as it would normally appear. Since emojis are text elements, I changed the cursor behavior but that’s just my preference for the purpose of this demo.
See the Pen Untitled by Andrew O’Connor (@AndrewOnTheWeb) on CodePen.
I think it’s easy to get caught up in all of the animations, fades, etc. in a UI. I like the small ones that make things a little easier and I think this is a good example.