This article demonstrates how to the use the CSS contrast filter function on elements with CSS filter. Included is code and examples.
The CSS contrast function is a value of CSS filter property. Contrast adjusts the contrast of the target HTML element. This can also include an image.
Syntax
filter: contrast(value);
Parameters
- value (required)
The value parameter of contrast is a number or percentage. A value over 100% increases contrast, while under 100% the contrast is decreased. The default value of contrast is 100%, which will leave an element unchanged. The default value is 1 when left unfilled. The initial interpolation value is 1.
Examples
The examples below use numbers and percentages values for the parameter of the contrast filter function.
contrast(1) /* No effect */
contrast(27%) /* A contrast of 27% */
contrast(35%) /* A contrast of 35% */
contrast(0.6) /* A contrast of 0.6 or 60% */
contrast(102%) /* A contrast of 17% */
contrast(1.7) /* A contrast of 1.7 or 170% */
Usage
You can apply the contrast filter to an image or any other element by using CSS selectors.
#element-id {
filter: contrast(120%);
}
img {
filter: contrast(0.75);
}
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: contrast(50%);
}
.wrapper img:nth-child(2) {
filter: contrast(100%);
}
.wrapper img:nth-child(3) {
filter: contrast(150%);
}
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-contrast