How to make scrolling snap to edges with CSS

The W3C Candidate Recommendation, CSS Scroll Snap Module Level 1, defines a specification for having scrolling snap to particular regions of the page. In other words, it is possible to create a ‘snap-to’ effect for scrolling on a webpage without JavaScript. To see the effect in action, try scrolling through the example sections in the following box.

Example section 1
Example section 2
Example section 3
Example section 4
Example section 5

The CSS for this example, with explanations in the comments, looks like this:

#example-snap-to {
	width: 300px;
	max-width: 100%;

	/* Needs a set height to force the overflow and
	   scroll effect */
	height: 150px;
	overflow-y: auto;

	/* On the y axis, it is mandatory that the scroll
	   snaps */
	scroll-snap-type: y mandatory;
	padding: 0;

#example-snap-to > div {
	display: grid;
	justify-content: center;
	align-items: center;
	background-color: olivedrab;

	/* This is the height of the container minus the
	   the width of the top and bottom borders so there
	   is no 'tail' on the last element. The content of
	   each section fits perfectly in the containing
	   div. */
	height: 146px;

	/* The scroll should snap to the start of the
	   element */
	scroll-snap-align: start;

It is applied to this HTML:

<div id="example-snap-to" class="example-block">
	<div>Example section 1</div>
	<div>Example section 2</div>
	<div>Example section 3</div>
	<div>Example section 4</div>
	<div>Example section 5</div>

Leave a Reply

Your email address will not be published.

Color scheme: