The CSS filter
property applies graphical effects like blurring or color shifting to an element. The contrast()
function is a part of the filter
property and is used to adjust the contrast of an element. A value of 0%
will create an image that is completely gray, while a value of 100%
will leave the image unchanged. Values greater than 100%
will increase the contrast.
Example 1: No Contrast
.no-contrast {
/* This sets the contrast of the image to 0% */
filter: contrast(0%);
}
Explanation
This code snippet targets an element with the class no-contrast
. It applies a contrast
value of 0%
, which removes all contrast, resulting in a completely gray element.
Example 2: Half Contrast
.half-contrast {
/* This reduces the contrast of the image by 50% */
filter: contrast(50%);
}
Explanation
Here, the half-contrast
class sets the contrast level to 50%
. This makes the dark areas lighter and the light areas darker, reducing the overall tonal difference in the element.
Example 3: Default Contrast
.default-contrast {
/* This leaves the image contrast unchanged */
filter: contrast(100%);
}
Explanation
The default-contrast
class applies a contrast
value of 100%
. This is the default value, so the element's appearance will not change.
Example 4: Increased Contrast
.increased-contrast {
/* This increases the contrast of the image by 50% */
filter: contrast(150%);
}
Explanation
This CSS rule targets the increased-contrast
class and increases the contrast by 50%
over the original. This makes the dark areas of the element darker and the light areas lighter, creating a more pronounced visual distinction.
Example 5: Doubled Contrast
.doubled-contrast {
/* This doubles the contrast of the image */
filter: contrast(200%);
}
Explanation
The doubled-contrast
class sets the contrast
to 200%
. This doubles the existing contrast, resulting in a very sharp and dramatic visual effect on the element.
Example 6: Using a Decimal Value
.decimal-contrast {
/* This increases the contrast slightly using a decimal value */
filter: contrast(1.2);
}
Explanation
The contrast()
function also accepts decimal values. In the decimal-contrast
class, a value of 1.2
is equivalent to 120%
, providing a slight boost in contrast.
Example 7: Combining with Other Filters
.combined-filter-contrast {
/* This applies both a contrast and a grayscale filter */
filter: contrast(175%) grayscale(50%);
}
Explanation
You can apply multiple filter functions at once. The combined-filter-contrast
class first increases the contrast to 175%
and then applies a 50%
grayscale effect to the element.