What is CSS Scroll Snap and How It Works
scroll-snap feature in CSS lets you control how scrolling stops at specific points, creating smooth and precise scroll positions. It helps make scrolling feel natural by snapping the view to elements like cards or sections automatically.How It Works
Imagine flipping through a photo album where each page snaps perfectly into place as you turn it. scroll-snap works similarly for web pages. When you scroll, instead of stopping anywhere, the page automatically locks onto predefined points, like the edges of images or sections.
This happens because you tell the browser where to 'snap' using CSS properties. You set a container to enable snapping and define snap points on child elements. When the user scrolls, the browser gently moves the view to the nearest snap point, making navigation smoother and more controlled.
Example
This example shows a horizontal list of colored boxes that snap into place as you scroll sideways.
html, body {
height: 100%;
margin: 0;
font-family: Arial, sans-serif;
}
.container {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
-webkit-overflow-scrolling: touch;
border: 2px solid #333;
padding: 10px;
gap: 10px;
}
.box {
flex: 0 0 200px;
height: 150px;
scroll-snap-align: start;
border-radius: 8px;
color: white;
font-size: 1.5rem;
display: flex;
align-items: center;
justify-content: center;
user-select: none;
}
.box1 { background-color: #e63946; }
.box2 { background-color: #f1faee; color: #1d3557; }
.box3 { background-color: #457b9d; }
.box4 { background-color: #2a9d8f; }
.box5 { background-color: #f4a261; color: #000; }When to Use
Use scroll-snap when you want to improve user experience by making scrolling feel neat and intentional. It is great for:
- Image galleries or carousels where each image snaps into view.
- Step-by-step guides or tutorials that scroll through sections one at a time.
- Product showcases with horizontal scrolling cards.
- Any interface where precise scroll positions help users focus on content.
It works well on both desktop and touch devices, making navigation easier and more enjoyable.
Key Points
- scroll-snap-type sets the snapping behavior on the container.
- scroll-snap-align defines where child elements snap.
- Works for both horizontal and vertical scrolling.
- Improves usability by controlling scroll stopping points.
- Supported in all modern browsers.