4 lines of background is all it takes to add scroll shadows that automatically appear when there's content to scroll and disappear when you hit the edge.
The Trick
The technique layers two types of background-attachment:
local β moves WITH the content (acts as a "cover")
scroll β stays FIXED to the container (the shadow)
When you scroll, the cover slides away and reveals the shadow underneath. It's like a curtain revealing what's behind it.
The Code
.scroll-container {
overflow-y: auto;
background:
linear-gradient(var(--bg) 33%, transparent) top,
linear-gradient(transparent, var(--bg) 66%) bottom,
radial-gradient(farthest-side at 50% 0,
rgba(0,0,0,.12), transparent) top,
radial-gradient(farthest-side at 50% 100%,
rgba(0,0,0,.12), transparent) bottom;
background-size:
100% 40px, 100% 40px,
100% 6px, 100% 6px;
background-repeat: no-repeat;
background-attachment:
local, local, scroll, scroll;
}
That's it. Works in every browser.
Why This Beats JS Solutions
Zero runtime cost
Works with any background color (just use a CSS variable)
Adapts to light/dark mode automatically
No layout shifts, no flickering
Works on any scrollable container
Credit
Credit to Lea Verou who pioneered this technique years ago. Still one of the most elegant CSS tricks out there.
Cover Photo by Susan Gold on Unsplash
Do you like what you are reading?. Subscribe to receive updates.
Unsubscribe anytime