Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Create Horizontal Scroll Snap Using HTML and CSS
To create a horizontal scroll snap, we use the CSS scroll-snap-type property to produce the snap effect. The properties scroll-snap-type and scroll-snap-align specify the type of snap behavior and the alignment of the snap points, respectively.
Syntax
/* Container */
.container {
scroll-snap-type: x mandatory;
overflow-x: scroll;
}
/* Items */
.item {
scroll-snap-align: start | center | end;
}
Key Properties
| Property | Value | Description |
|---|---|---|
scroll-snap-type |
x mandatory |
Enables mandatory horizontal scrolling snap |
scroll-snap-align |
start |
Aligns snap points to the start of each section |
overflow-x |
scroll |
Enables horizontal scrolling when content overflows |
Example
The following example creates a horizontal scroll snap with multiple sections
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Horizontal Scroll Snap</title>
<style>
.container {
width: 100%;
height: 100vh;
overflow-x: scroll;
scroll-snap-type: x mandatory;
display: flex;
background-color: #f0f0f0;
}
.section {
min-width: 100%;
height: 100vh;
scroll-snap-align: start;
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
font-weight: bold;
color: white;
}
.section:nth-child(1) { background-color: #FF6B6B; }
.section:nth-child(2) { background-color: #4ECDC4; }
.section:nth-child(3) { background-color: #45B7D1; }
.section:nth-child(4) { background-color: #96CEB4; }
</style>
</head>
<body>
<div class="container">
<div class="section">Section 1</div>
<div class="section">Section 2</div>
<div class="section">Section 3</div>
<div class="section">Section 4</div>
</div>
</body>
</html>
A full-width horizontal scrollable container with four colored sections. Each section takes up the full viewport width and height. When scrolling horizontally, the container snaps to the start of each section, creating a smooth page-by-page navigation effect. Section 1 is red, Section 2 is teal, Section 3 is blue, and Section 4 is green.
Browser Support
CSS scroll snap is supported in all modern browsers. For older browser compatibility, consider using JavaScript polyfills or libraries for enhanced scroll snap functionality.
Conclusion
Horizontal scroll snap creates an intuitive navigation experience for users browsing through sections like image galleries, product carousels, or portfolio sections. The combination of scroll-snap-type and scroll-snap-align provides precise control over the snapping behavior.
