Blog

#css

#scroll-snap

Scroll Snap for a Nice Mobile Experience

Small enhancement to homepage. Two column layout, so mobile normally would make that one column. Which it had. But I write a few featured posts and lots of “other” posts. The sidebar had the “other” posts, but that got put way down the page. You’re unlikely to get there through scrolling. But putting it first wouldn’t make sense because then the featured posts are too far.

So… I made a scroller using the new scroll-snap CSS functionality. Now you can see the latest “other”, but it doesn’t push the featured posts down 3 scroll heights.

.b--article-list {
	display: flex;
	width: calc(100vw - 64px);
	overflow-x: scroll;
	scroll-snap-type: x mandatory;
	scroll-padding-right: 20%;

	> * {
		min-width: calc(80% - 32px);
		padding-left: 32px;
		scroll-snap-align: start;
	}
}

With scroll-snap-type set to x mandatory, we allow card-based scrolling horizontally. Setting the scroll-snap-align to start for all children makes the snap point the left side of each card.

I have implemented this style of interface before, almost a decade ago. It took a lot of JavaScript. Now with just a few lines of CSS, you get a super interactive little component.

Demo: Homepage view on mobile or scale down and you’ll see the Ramblin’ section using the above.