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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Ampersand (Parent Selector) in SCSS (Sass)SCSSCreate a galley with overlapping images using CSS gridCSSHow to convert an object from API to JSON array in Angular 9?AngularHow to modify navigation menus in WordPress?WordPressHow to add multiple components in React app?ReactCurrencyPipe in Angular 9 with ExamplesAngular