I am working on a web project where I need to create a vertically scrollable list. My objective is to have the list automatically snap to the nearest item, aligning it to the center of the list, whenever the user stops scrolling.
I’ve tried a CSS approach, where I applied scroll-snap-type to the list container and scroll-snap-align to each list item. This doesn’t seem to work correctly.
Is there a pure CSS solution to ensure the nearest item always snaps to the center upon scroll? Or do I need to use JavaScript to calculate the scroll position and adjust it dynamically? If JavaScript is required, how should I approach this?
Any insights or suggestions on how to achieve this functionality would be greatly appreciated.
.wrapper {
width: 100vw;
height: 100vh;
background-color: #e5ddde;
display: flex;
justify-content: center;
}
li {
text-transform: uppercase;
font-family: Futura;
font-size: 40px;
color: grey;
scroll-snap-align: center;
}
li.active {
color: black;
}
ul {
list-style: none;
scroll-behavior: auto;
scroll-snap-type: y mandatory;
}
<div class "wrapper">
<ul>
<li>Name One</li>
<li>Name Two</li>
<li>Name Three</li>
<li class="active">Name Four -----</li>
<li>Name One</li>
<li>Name Two</li>
<li>Name Three</li>
<li>Name Four</li>
<li>Name One</li>
<li>Name Two</li>
<li>Name Three</li>
<li>Name Four</li>
<li>Name One</li>
<li>Name Two</li>
<li>Name Three</li>
<li>Name Four</li>
</ul>
</div>
