I am struggling with scroll-snap in CSS.
Is there a way to use scroll-snap only in one vertical direction?
I want to make it snap on every section when scrolling down, but not to snap when scrolling back up again. Is it possible inside CSS or do I need some JavaScript?
html {
scroll-snap-type: y mandatory;
}
body {
margin: 0;
scroll-snap-type: y mandatory;
}
section {
font-family: sans-serif;
font-size: 12ch;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
scroll-snap-align: start;
}
<head>
<!-- MAIN STYLE -->
<link rel="stylesheet" href="style.css">
</head>
<main>
<section>
<h1>Hello!</h1>
</section>
<section>
<h1>Toodles~</h1>
</section>
<section>
<h1>Boodles~</h1>
</section>
</main>
</html>
You could listen the the scroll event and set the scroll-snap-type property to the html element according to the scroll direction.
//save initial scrollY position
var previousScrollY = window.scrollY;
//listen to scroll event
window.addEventListener("scroll", function(e) {
//is the user scrolling down ?
let down = window.scrollY > previousScrollY;
//set scroll-snap-type according to scroll direction
document.documentElement.style.scrollSnapType = down ? "y mandatory" : "";
//save current scrollY position
previousScrollY = window.scrollY;
});
body {
margin: 0;
}
section {
font-family: sans-serif;
font-size: 12ch;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
scroll-snap-align: start;
}
<section>
<h1>Hello!</h1>
</section>
<section>
<h1>Toodles~</h1>
</section>
<section>
<h1>Boodles~</h1>
</section>
As per my research, no solution using CSS, and to achieve this use a javascript window scroll event and on scroll up remove the scrollSnapType CSS property.