Header

Pure CSS drop shadow on scroll

This pen demonstrates how we can use CSS to let a drop-shadow appear below a header bar when we start to scroll the page.

Scroll the page to see the effect.

This effect is used in Material Design, so for the Pure CSS Material Design library I am building, I needed to implement this drop-shadow. But Google implements this with a class on the body that is activated on scroll by some piece of Javascript that listens to the onscroll event. For a Pure CSS solution, I needed a different approach.

For a long time I thought the effect would be impossible to achieve as there are no events in CSS and there is no :scrolled pseudo class like we have with :checked for checkboxes. But then I got an idea. I realized that elements with position:sticky do respond to scroll behavior. Surely I could use this somehow to have a shadow slide down when we scroll?

Well, I have not found a practical way to have something move down when the page scrolls down. The direction of the movement must be the same as the content, so opposite the scroll direction (when we scroll down, the content appears to move up). Maybe we could do something with transform here, but I did not investigate.

Instead, I came up with another idea. What if, instead of the shadow appearing from behind the header, we could use a cover element that would hide the shadow initially and then reveal it on scroll?

It took a couple of hours hacking around with position:sticky before I managed to implement the effect, but the approach does work! In all modern browsers... except.. Edge. Unfortunately Edge has a bug at the moment relating to nested sticky elements that breaks the effect. But the good news is that it's apparently already fixed and should be released in the next upcoming version. So hopefully once that releases, this effect will work cross-browser.

Also read my blog post about this codepen.