CSS has come a long way over the last few years. In today’s post we’ll take a look at how we can add a black and white filter to our user interface.
The CSS filter
property allows you to apply many graphical effects to your HTML markup including images, divs, and other elements. The grayscale()
filter allows you to convert an image to various shades of gray, including black and white.
Using the Grayscale CSS Filter
To use the grayscale filter, you call the function as a property value to your filter
property like so:
img {
filter: grayscale(100%);
}
The above CSS will make all images on your page black and white. You can fine tune the percentage from 0% to 100%. Additionally, you can use an integer value from 0 to 1 to denote the percentage as well. The following example show how to do just that.
img {
filter: grayscale(1);
}
Additionally, if you omit any value in the grayscale()
filter the result will be equivalent to setting it to 1 or 100%.
img {
filter: grayscale(); /* Same as grayscale(1) */
}
Pretty easy right? You can apply this filter both to images and other elements on your page such as div’s, SVGs, and so on.
CSS Black and White Image Example
Let’s see this filter in action. We’ll use an image from Unsplash by Jeryy Zhang .
Base Image
Grayscale(1) a.k.a black and white
Our code will look like this:
.black-and-white {
filter: grayscale(); /* Same as grayscale(1) */
}
Grayscale(50%) a.k.a half black and white
Our code will look like this:
.grayscale-50 {
filter: grayscale(50%);
}
CSS Black and White HTML Example
Next, let’s do the same but this time with an html element. Let’s create a box and give it the color magenta. The code will look like this:
.box {
height: 75px;
width: 100px;
padding: 25px;
text-align: center;
background: magenta;
color: white;
}
<div class="box">Hello!</div>
And our result:
Now, if we add any of the above classes like grayscale-50
or black-and-white
we’ll see the changes applied just like they were to the image.
Black and white
<div class="box black-and-white">Hello!</div>
Grayscale-50
<div class="box grayscale-50">Hello!</div>
Pretty cool right? The grayscale()
filter works in most modern browsers and is a great way to add the black and white effect to your user interface.