Yogesh Chauhan's Blog

Control Scrolling with CSS Scroll Snap

in CSS on July 22, 2021

CSS Scroll Snap feature allows you to control a scrolling experience on a specific element.

In order to do that, you need to declare scroll snapping positions.

Generally this feature is useful with image carousels or sliders where you need to push a container and bring the next one into focus.

scroll-snap-type

To enforce strict scrolling on a container, you need to use scroll-snap-type property.

Values

Main keyword values are none, x, y, both, block and inline.

Optionally you can also add a value next to the main keyword values from these two values: mandatory or proximity.

The global values work as well if parent element has scroll-snap-type property defined. You can inherit, initial or unset (in-case you don’t want to enforce it).

scroll-snap-align

You also need to specify scroll-snap-align property for the child elements of the main container in order to set the alignment within the container.

The value are none, start, end and center. You can also use start end together, in that case the first block is set as start and the second as inline.

Examples

Without controlled Scrolling

scroll-snap-type: none

It’s basically same result.

scroll-snap-type: x mandatory

Look at this controlled scrolling now:

With mandatory scroll type, the scroll offset will be adjusted as you can see in the example above.

The same rule applied to scroll-snap-type: y mandatory


scroll-snap-type: x proximity

With proximity scroll type, the scroll offset may get adjusted or may not.

The same rule applied to scroll-snap-type: y proximity

In a 2D image grid, you might want to set scroll-snap-type: both mandatory to make it scrollable on both axis while forcing a mandatory snap view.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Effects in ReactReactCROSS JOIN in PostgresPostgresHow to create Glowing Texts using CSS?CSSIntroduction to components and templates Part 4: Pipes and DirectivesAngularWordPress: How to display fields from ACF Flexible Contents?WordPressHow to create a simple digital clock using JavaScript?JavaScript