CSS filter for Image States
Lesson 32 of 41 in the CSS3 learning path.
How do I grayscale an image until it is hovered?
filter applies graphical effects to an element. grayscale and drop-shadow are enough for a catalog thumbnail.
One photo can serve the resting card and the hovered card. You do not export two assets.
Syntax & Parameters
img { filter: grayscale(1); } img:hover { filter: none; }
Example
Interactive preview available.thumb img {
width: 100%;
height: 8rem;
object-fit: cover;
filter: grayscale(1);
transition: filter .2s linear;
}
.thumb:hover img,
.thumb:focus-within img {
filter: none;
}
.thumb img.badge {
filter: drop-shadow(0 6px 8px rgb(15 23 42 / .25));
}
Expected Output
Thumbnails are gray until the card is hovered or focused. A badge image keeps a soft shadow around its shape.
Line-by-Line Walkthrough
- The image fills the thumb frame with object-fit.
- grayscale 1 removes color in the resting state.
- A short transition fades the filter.
- Hover and focus-within restore full color.
- focus-within covers keyboard users inside the card link.
- The badge uses drop-shadow, which follows the alpha of the image.
- box-shadow would shadow the rectangle, not a cut-out logo.
- Do not animate filter on dozens of large images if the page already struggles.
Common Pitfalls & Security
Watch the failure mode, not only the happy path.
- filter on a huge photo is more expensive than opacity.
- Hover-only color hides the picture from keyboard users unless focus-within is included.
- grayscale is not a loading state. It looks like a disabled image.
- drop-shadow on a fully opaque rectangle looks the same as box-shadow and costs more.
Best Practices & Modern Standards
Use filter for a simple state change on a small thumbnail.
Include a focus path. Prefer opacity or a class toggle if you need the effect on a long list.
Real-World Use
Instructor portraits on the catalog are quiet until the card is pointed at or tabbed to. The department logo uses drop-shadow because it is a transparent PNG.
Frequently Asked Questions
Is grayscale a disabled style?
It can look that way. Do not use it for a control that is actually unavailable.
How is drop-shadow different from box-shadow?
drop-shadow follows transparent pixels. box-shadow follows the element box.
Does filter affect text?
Yes, if you put it on a parent. Put it on the image, not the card.
Should I animate it?
A short transition is fine on a few thumbs. Skip it on a long scrolling list.