DEV Community

Cover image for Applying Styles Based on the User Scroll Position with Smart CSS

Applying Styles Based on the User Scroll Position with Smart CSS

Rik Schennink on January 25, 2019

By mapping the current scroll offset to an attribute on the html element we can style elements on the page based on the current scroll position. We...
Collapse
 
link2twenty profile image
Andrew Bone • Edited

You can use position:sticky; to save a little bit of code too.

Collapse
 
rikschennink profile image
Rik Schennink

Nice, Thanks Andrew!

Just checked sticky browser support and it's actually quite great.

Sticky Browser Support Table

I also noticed the demo didn't work on Safari, it seems it still needs the -webkit- prefix.

header {
  position: sticky;
  position: -webkit-sticky;
}
Collapse
 
emgodev profile image
Michael

WHY DIDN'T I THINK OF THIS!? This is just like frontend reactive framework one way data flow, update the att, and let CSS handle applying the styles, no need to conditionally add a class at a certain breakpoint!

Collapse
 
rikschennink profile image
Rik Schennink

Haha :D I felt exactly the same when I first set this up, it's a very straightforward and flexible way of solving these kinds of problems :-)

Collapse
 
thejase profile image
Jason Featheringham

Won’t this only work for a single scroll point vs all others? Seems pointless to continually update the attribute instead of just adding a binary class.

Collapse
 
rikschennink profile image
Rik Schennink

The idea behind it is two-fold, one, you got the data, why not share it with CSS. Two, the JavaScript logic is as dumb as it gets, no knowledge of classes or naming or behavior that is attached. By keeping the JavaScript this basic it's less prone to errors or growth due to edge cases.

For non-binary situations:
dev.to/rikschennink/using-smart-cs...

I'm not saying one or the other is better, it is simply an interesting alternative approach.