This article demonstrates how to the use the CSS grayscale filter function on elements with CSS filter. Included is code and examples.
The CSS grayscale function is a value of the CSS filter property. Grayscale applies a grayscale to the target HTML element. This can also include an image. When grayscale is applied, colors are converted to white, gray, and blacks based on a range value.
Syntax
filter: grayscale(value);
Parameters
- value (required)
The value parameter of grayscale is a number or percentage. A value over 0%, is more grayscale, while 100% is fully converted to grayscale. The range is linear, so each increase or decrease in the value is equal. When grayscale is not supplied a number the default is 0 and when 0% or 0 is supplied it leaves the element unchanged. For interpolation, the initial value is 0.
Examples
The examples below uses numbers and percentages values for the parameter of the grayscale filter function.
grayscale(0) /* No effect */
grayscale(27%) /* A grayscale of 27% */
grayscale(35%) /* A grayscale of 35% */
grayscale(0.6) /* A grayscale of 0.6 or 60% */
grayscale(0.7) /* A grayscale of 0.7 or 70% */
grayscale(100%) /* Completely grayscale */
grayscale(1) /* Completely grayscale */
Usage
You can apply the grayscale filter to an image or any other element by using CSS selectors.
#element-id {
filter: grayscale(70%);
}
img {
filter: grayscale(0.25);
}
Try It
HTML
<div class="wrapper">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/46992/noah-silliman-141979.jpg" alt="" />
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/46992/noah-silliman-141979.jpg" alt="" />
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/46992/noah-silliman-141979.jpg" alt="" />
</div>
CSS
.wrapper img {
width: 300px;
height: 300px;
object-fit: cover;
border-radius: 6px;
margin: 0 20px;
vertical-align: middle;
}
.wrapper img:nth-child(1) {
filter: grayscale(0%);
}
.wrapper img:nth-child(2) {
filter: grayscale(50%);
}
.wrapper img:nth-child(3) {
filter: grayscale(100%);
}
html {
text-align: center;
min-height: 100%;
background: linear-gradient(white, #ddd);
}
.wrapper {
width: 100%;
background: transparent;
text-align: center;
-webkit-box-align: center !important;
-ms-flex-align: center !important;
align-items: center !important;
-webkit-box-pack: center !important;
-ms-flex-pack: center !important;
justify-content: center !important;
display: -webkit-box !important;
display: -ms-flexbox !important;
display: flex !important;
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
}
Specifications
W3C CSS Filter Effects Module Level 1
#funcdef-filter-grayscale