Select Page

Category: attribute selectors

Styling Based on Scroll Position

Rik Schennink documents a system for being able to write CSS selectors that style a page when it has scrolled to a certain point. If you’re like me, you’re already on the lookout for document.addEventListener('scroll' ... and being terrified about performance. Rik gets to that right away by both debouncing the function as well as marking the event as passive. The end result is a data-scroll attribute on the element that can be used in the CSS. Meaning if you’re scrolled to 640px down the page, you have and could write a selector like: html:not([data-scroll='0']) { body { padding-top: 3em; } header { position: fixed; } } See the Pen Writing Dumb JS 🧟‍♂️ and Smart CSS 👩‍🔬 by Rik Schennink (@rikschennink) on CodePen. Unfortunately, we don’t have greater than (>) less than (<) selectors in CSS for things like numbered attributes, so the CSS styling potential is fairly limited here. You might ultimately need to update the JavaScript function such that it applies other classes or data attributes based on your math. But you’ll already be set up for good performance here. “Apply styles when the user has scrolled away from the top” is a legit use case. It makes me think of a once function (like we have in jQuery) where any scroll event would only be triggered once and then not again. They scrolled! So, by...

Read More
www.000webhost.com