Monochromey CSS

#css #imaging

Written by Anders Marzi Tornblad

Published on dev.to

Photo of a forest and a waterfall, where half the image is a monochromatic green scale.Let's say you have a photo that you want to show somewhere on a web page. The photo is rich in color, but you need to follow a strict color scheme, maybe because of brand guidelines, or just because you like certain colors more than others.

The first temptation might be to open the photo in your favorite image editor software (mine is Paint.NET for the PC) and fiddle around with functions until the photo looks the way you want it.

Then, after a while, the color scheme changes for some reason. Maybe the higher-ups emerge from a meeting room after a rebranding workshop, or maybe you just get tired of mauve and decide that perriwinkle blue is your new favorite color. You discover that your site has hundreds of photos that all need to be re-edited. To avoid this, you should instead serve the original photo as it is, and let CSS filters do the trick for you.

If you go for the grayscale filter, you get a photo that is all grays. If you want a completely desaturated image, this works fine. But if you are aiming for a monochromatic image of a certain hue, grayscale is a dead end. Instead, start by applying the sepia filter, which sets the hue of every pixel of the image to somewhere around 60°. Then you can add another filter to add or subtract to the hue.

img.monochrome {
    filter: sepia() hue-rotate(123deg);
}

I made a Pen to demonstrate the effect. Drag the hue selector to the desired color and copy the generated CSS. If you hold down your finger (or the mouse button) on the image, the filter effect is cancelled to reveal the original image. The image itself is a random Unsplash image with nature, water as the query.