Scroll Snap Align in CSS
Hello friends! Today we want to talk about one of the cool features of CSS called Scroll Snap Align. This feature allows you to have better control over how web pages scroll. Simply put, by using this feature, you can create specific elements to snap to a "contact point" when scrolling. In other words, when a user scrolls, it helps them determine which part of the page is currently the "focus point".
In the world of modern websites, especially when dealing with galleries or long lists, this feature is quite useful. You might want to ensure that when a user reaches a specific section of a page, all the focus is on that section while the other parts are placed in the background. That's what scroll-snap-align does!
Now let's take a look at how to use this feature. The common understanding is that instead of simply writing CSS code, we should be careful about the details as well! This feature should be used in conjunction with the heights and characteristics of touch or mouse scrolls to achieve the best results.
Scroll Snap Align is typically used with scroll-snap-type in the parent and scroll-snap-align in the children. This combination gives you the ability to control the precise behavior of the scrolling page elements. Now let’s take a look at the code!
Item 1
Item 2
Item 3
Item 4
<style>
.scroll-container {
display: flex;
overflow-x: scroll;
scroll-snap-type: x mandatory;
}
.snap-item {
flex: none;
width: 300px;
height: 200px;
margin: 10px;
background-color: lightblue;
scroll-snap-align: start;
}
</style>
In the code above, we have a "scroll-container" that contains several "snap items". In this <div>
, we simply use display: flex;
to arrange the elements side by side. According to overflow-x: scroll;
, it allows us to scroll horizontally.
The most critical part of this section is scroll-snap-type: x mandatory;
, which enables the elements to snap into place when scrolling. Next, we turn to <div class="snap-item">
, which represents the individual items in the container. With the help of scroll-snap-align: start;
, we can specify which item should be "focused" when scrolling stops.