0
0
CssHow-ToBeginner · 3 min read

How to Use Grayscale Filter in CSS: Simple Guide

Use the filter property in CSS with the grayscale() function to make an element appear in black and white. For example, filter: grayscale(100%); turns the element fully gray, while filter: grayscale(50%); applies a half grayscale effect.
📐

Syntax

The filter property applies graphical effects like grayscale to elements. The grayscale() function takes a value from 0% (no effect) to 100% (full grayscale).

  • filter: CSS property to apply visual effects.
  • grayscale(value): Function where value is a percentage or decimal between 0 and 1.
css
selector {
  filter: grayscale(100%); /* full grayscale effect */
}
💻

Example

This example shows an image with a full grayscale filter applied. The image will appear in black and white.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grayscale Filter Example</title>
<style>
  img {
    width: 300px;
    filter: grayscale(100%);
    transition: filter 0.3s ease;
  }
  img:hover {
    filter: grayscale(0%);
  }
</style>
</head>
<body>
  <img src="https://via.placeholder.com/300" alt="Sample Image">
</body>
</html>
Output
A 300px wide placeholder image shown in black and white that returns to color when hovered over.
⚠️

Common Pitfalls

Common mistakes when using the grayscale filter include:

  • Using values outside the 0 to 1 or 0% to 100% range, which will be ignored or cause no effect.
  • Forgetting to add filter to the correct selector or element.
  • Expecting the filter to work in older browsers without support.

Always test in modern browsers and use fallback styles if needed.

css
/* Wrong: value out of range, no effect */
img {
  filter: grayscale(150%); /* invalid value */
}

/* Correct: valid value */
img {
  filter: grayscale(100%);
}
📊

Quick Reference

PropertyDescriptionExample
filterApplies visual effects to elementsfilter: grayscale(50%);
grayscale(0%)No grayscale effect, original colorsfilter: grayscale(0%);
grayscale(100%)Full grayscale, black and whitefilter: grayscale(100%);
grayscale(0.5)50% grayscale effect using decimalfilter: grayscale(0.5);

Key Takeaways

Use the CSS filter property with grayscale() to make elements black and white.
Grayscale values range from 0 (no effect) to 1 or 100% (full grayscale).
Test filters in modern browsers for consistent results.
You can animate or change grayscale on hover for interactive effects.
Avoid invalid values outside the 0 to 1 or 0% to 100% range.