
(Learning video sharing: css video tutorial)
Have you often wished there was a CSS feature that could easily create a scrollable container? CSS scroll snap can do this. In my early days of front-end development, I relied on JS plugins to create slider components. Sometimes, we need a simple way to quickly make an element into a scrollable container. Now, thanks to CSSS scroll snap we can do this simply.
Why use CSS Scroll Snap
With the rise of mobile and tablet devices, we need to design and build components that can be tapped. Take the gallery component as an example. Instead of a hierarchical structure, users can easily swipe left or right to see more images.

According to the CSS specification, providing developers with a well-controlled scrolling experience is one of the main reasons for the introduction of CSS scroll snap. It enhances the user experience and makes it easier to achieve a scrolling experience.
Basics of rolling containers
To create a rolling container, here are the basics of what we need to do
- Using
overflow - A way to display items next to each other (inline)
For example:
<div> <div>Item 1</div> <div>Item 2</div> <div>Item 3</div> <div>Item 4</div> <div>Item 5</div> </div>
.section {
white-space: nowrap;
overflow-x: auto;
}
For years, use white-space: nowrap is a popular CSS solution for forcing elements to stay inline. However, now we basically use Flexbox :
.section {
display: flex;
overflow-x: auto;
}

This is the basic method of creating a rolling container. However, this is not enough, this is not a usable scroll container.
What’s wrong with scrolling containers
The problem is that they don’t provide a good experience compared to sliding. The main benefit of swipe gestures on touch screens is that we can scroll horizontally or vertically with one finger.

Each item actually needs to be moved to it's own location. This is not sliding, it is a very bad experience, by using CSS scroll snap we can solve this problem by simply defining snap points, it will make the user more Easily scroll horizontally or vertically.
Next, let’s take a look at how to use CSS scroll snap.
Introduction to CSS Scroll Snap
To use scroll snap on a container, its child items should be displayed inline, this can be done using one of the methods I explained above accomplish. I chose CSS flexbox:
<div> <div>Item 1</div> <div>Item 2</div> <div>Item 3</div> <div>Item 4</div> <div>Item 5</div> </div>
.section {
display: flex;
overflow-x: auto;
}
for this, we need to add two more properties to make scroll snap work. Where should we add them?
First, we need to add scroll-snap-type to the scroll container. In our example, it's the .section element. Then we need to add scrolln-snap-align to the child item (i.e. .section__item).
.section {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
}
.section__item {
scroll-snap-align: start;
}
Here you may want to know what x mandatory and start are used for. Don’t worry, this is the core of this article and will be explained in depth below.

At this moment, I am very excited about CSS scroll snap, it makes scrolling more natural. Now, let's delve into the scroll snap properties.
Scroll Snap Type
According to the CSS specification, the scroll-snap-type attribute defines how a temporary point (snap point) in the scroll container is strictly enforced.
The axis of the scroll container
The axis of the scroll container represents the scroll direction, it can be horizontal or vertical, the x value represents horizontal scrolling, and y means vertical scrolling.
/* 水平*/
.section {
display: flex;
overflow-x: auto;
scroll-snap-type: x;
}
/* 垂直*/
.section {
height: 250px;
overflow-y: auto;
scroll-snap-type: y;
}

Scroll Snap Container Strictness
We can not only define the direction of the Scroll Snap, but also its strictness. This can be achieved by using andatory | proximity with the scroll-snap-type value.
mandatory: If it is not currently scrolled, the visual view of this scroll container will remain at the temporary point. Meaning when the scrolling action ends, it will be at that point temporarily if possible. If content is added, moved, deleted, or resized, the scroll offset will be adjusted to remain stationary at the temporary point. The
mandatory keyword means that the browser must capture every scroll point. Assume that the roll-snap-align attribute has a start value. This means that the scroll must be aligned to the beginning of the scroll container.
在下图中,每次用户向右滚动时,浏览器都会将项目捕捉到容器的开头。

.section {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
}
.section__item {
scroll-snap-align: start;
}

试着在下面的演示中向右滚动。如果你使用的是手机或平板电脑,可以向右移动滚动条或使用触摸。应该能感受到每个项目是如何从其容器的开始抓取的。
演示地址:https://codepen.io/shadeed/pen/RwGaXKB
但是,如果该值是proximity,则浏览器将完成这项工作,它可能会吸附到定义的点(在我们的例子中start)。注意,proximity 是默认值,但是为了清晰起见,我们这里还是声明一下它。

.section {
display: flex;
overflow-x: auto;
/* proximity is the default value, I added it for clarity reasons */
scroll-snap-type: x proximity;
}

Scroll Snapping Alignment
滚动容器的子项目需要一个对齐点,它们可以对齐到这个点。我们可以用start, center或end。
为了更容易理解,下面是它的工作原理。

假设我们在滚动容器上有一块磁铁,这将有助于我们控制捕捉点。 如果scroll-snap-type是垂直的,则对齐对齐将是垂直的。 参见下图:

滚动容器的 start
子项目将吸附到其水平滚动容器的开始处。

滚动容器的 center
子项目将吸附到其滚动容器的中心。

滚动容器的 end
子项将对齐到其滚动容器的末尾。

使用 Scroll-Snap-Stop
有时,我们可能需要一种方法来防止用户在滚动时意外跳过一些重要的项。如果用户滚动太快,就有可能跳过某些项。
.section__item {
scroll-snap-align: start;
scroll-snap-stop: normal;
}
法动太快可能会跳过三个或四个项目,如下所示:

scroll-snap-stop的默认值是normal,要强制滚动捕捉到每个可能的点,应使用always。
.section__item {
scroll-snap-align: start;
scroll-snap-stop: always;
}

这样,用户可以一次滚动到一个捕捉点,这种方式有助于避免跳过重要内容。 想象每个停止点都有一个停止标志,参见下面的动画:

演示地址:https://codepen.io/shadeed/pen/JjRbXza
Scroll Snap Padding
scroll-padding设置所有侧面的滚动边距,类似于padding属性的工作方式。 在下图中,滚动容器的左侧有50px的内边距。 结果,子元素将从左侧边缘捕捉到50px

直滚动也是如此。参见下面的示例:
.section {
overflow-y: auto;
scroll-snap-type: y mandatory;
scroll-padding: 50px 0 0 0;
}

Scroll Snap Margin
scroll-margin设置滚动容器的子项之间的间距。 在向元素添加边距时,滚动将根据边距对齐。 参见下图:

.item-2具有scroll-margin-left: 20px。 结果,滚动容器将在该项目之前对齐到20px。 请注意,当用户再次向右滚动时,.item-3会捕捉到滚动容器的开头,这意味着仅具有边距的元素将受到影响。
CSS Scroll Snap 用例
图片列表
scroll snap 的一个很好的用例是图像列表,使用 scroll snap 提供更好的滚动体验。

.images-list {
display: flex;
overflow-x: auto;
scroll-snap-type: x;
gap: 1rem;
-webkit-overflow-scrolling: touch; /* Important for iOS devices */
}
.images-list img {
scroll-snap-align: start;
}
注意,我使用x作为scroll-snap-type的值。

事例地址:https://codepen.io/shadeed/pe...
好友清单
滚动捕捉的另一个很好的用例是朋友列表。 下面的示例摘自Facebook(一个真实的示例)。

.list {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
gap: 1rem;
scroll-padding: 48px;
padding-bottom: 32px;
-webkit-overflow-scrolling: touch;
}
.list-item {
scroll-snap-align: start;
}
请注意,滚动容器的padding-bottom:32px。 这样做的目的是提供额外的空间,以便box-shadow可以按预期显示。

头像列表
对于此用例,我感兴趣的是将center作为scroll-snap-align的值。

.list {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
-webkit-overflow-scrolling: touch;
}
.list-item {
scroll-snap-align: center;
}
这在一个角色列表中是很有用的,角色在滚动容器的中间是很重要的

演示地址:https://codepen.io/shadeed/pen/KKgMJWa
全屏展示
使用scroll snap也可以用于垂直滚动,全屏展示就是一个很好的例子。

<main> <section></section> <section></section> <section></section> <section></section> <section></section> </main>
main {
height: 100vh;
overflow-y: auto;
scroll-snap-type: y mandatory;
-webkit-overflow-scrolling: touch;
}
.section {
height: 100vh;
scroll-snap-align: start;
}

块和内联
值得一提的是,对于scroll-snap-type,可以使用inline和block逻辑值。参见下面的示例
main {
scroll-snap-type: inline mandatory;
}
可读性
使用 CSS scroll snap时,请确保可访问性。 这是滚动对齐的一种不好用法,它阻止用户自由滚动内容以读取内容。
.wrapper {
scroll-snap-type: y mandatory;
}
h2 {
scroll-snap-align: start;
}
请务必不要这样做。
总结
这是我刚刚学到的一个新的CSS特性的长篇文章。我希望它对你有用。
原文地址:https://ishade.com/article/css-scroll-snap/
作者:Ahmad
译文地址:https://segmentfault.com/a/1190000038459089
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Tips for optimizing scrolling: Use CSS Scroll Snap! !. For more information, please follow other related articles on the PHP Chinese website!
How to create a hover effect on a table row in CSSAug 26, 2025 am 07:29 AMTo create a hover effect for table rows, you need to use the CSS :hover pseudo-class. It is recommended to set background color, text color and other styles for cells in the row through tr:hovertd to ensure compatibility. You can combine transitions to achieve smooth transitions and cursor:pointer prompts interactivity. You can also distinguish between processing table headers and data rows through class names to avoid style conflicts, and ultimately achieve a simple and efficient hover effect.
How to use box-sizing: border-box in CSSAug 26, 2025 am 07:18 AMUsingbox-sizing:border-boxensuresanelement’sdeclaredwidthincludesitscontent,padding,andborder,preventingunexpectedlayoutoverflow;applyingitgloballyvia,::before,*::after{box-sizing:border-box;}standardizessizingacrossallelementsandpseudo-elements,maki
How to style a horizontal rule (hr) with CSSAug 26, 2025 am 07:11 AMTo completely customize the horizontal line style, you must first remove the default style, and then use the background, border and other properties of CSS to redefine the appearance. The specific method is to first set border:none to clear the browser's default style. Then you can create custom lines through background-color or border-top. It is recommended to use background-color to obtain higher control. If you need a dotted line or dotted line effect, use border-top and match dashed, dotted and other values. By setting width and margin:auto, you can control the line width and achieve horizontal centering. Use linear-gradient to create gradient effects on the background.
How to style a file input button with CSSAug 26, 2025 am 06:48 AMTo customize the style of the file upload button, you need to hide the native input box and replace it with a label. By setting the input box to be transparent and absolutely positioned, it is overlaid on the styleable label, thus achieving a fully customizable appearance while retaining functionality and accessibility. This method is compatible with all browsers and supports displaying file names, hover status and keyboard navigation, and ultimately creating a file upload button that is both beautiful and practical.
How to use CSS scroll-behavior for smooth scrolling?Aug 26, 2025 am 06:15 AMTo achieve smooth scrolling on web pages, you need to use the scroll-behavior attribute of CSS; 1. Apply scroll-behavior:smooth to the html element to enable global smooth scrolling; 2. When clicking an anchor link (such as #section), animated scrolling is triggered instead of instant jumps; 3. It is recommended to set it on html instead of body to ensure compatibility; 4. This property can be applied separately in a custom scroll container to achieve local smooth scrolling; 5. Note that JavaScript scrolling operations can override this effect through behavior:'auto'; this method is compatible with modern mainstream browsers and significantly improves the user experience, which can be easily implemented with one sentence of CSS.
How to create a modal window in CSSAug 26, 2025 am 06:04 AMUse hidden check boxes as status switches to control the display and hiding of modal boxes through the checked selector of CSS; 2. Use label's for attribute to associate check boxes to achieve opening and closing operations; 3. Use adjacent brother selectors ( ) to display modal boxes when the check box is selected; 4. Add appropriate styles to achieve visual effects such as centering, masking, rounding corners, shadows, etc.; 5. Ensure accessibility, add aria-hidden and role attributes, and ensure that the keyboard is operable. This method can create a modal window with complete functionality, clear structure and easy to maintain without JavaScript, suitable for simple prompts or information display scenarios.
How to use the @supports rule in CSSAug 26, 2025 am 05:53 AM@supports rules are used to implement progressive enhancement based on whether the browser supports specific CSS attributes or values. 1. The basic syntax is @supports(property:value){...}. If display:grid is supported, the grid layout is applied. 2. The conditions can be combined using and, or, and not logical operators, such as supporting multiple features at the same time or providing a fallback scheme. 3. Support grouping complex conditions in brackets and can be nested with other at rules such as @media. 4. In actual applications, it is recommended to set basic styles and gradually enhance them to avoid excessive use, ensure that browsers that do not support new features can still display content normally, and ultimately achieve the effect of safely adopting modern CSS.
How to style form inputs with CSSAug 26, 2025 am 12:02 AMTo effectively and consistently beautify form input across browsers, the following steps must be followed: 1. Use standard CSS properties to customize the appearance of text input, password, mailbox, etc., set width, margins, borders, rounded corners and fonts, and add interactive feedback through the:focus pseudo-class; 2. Use the ::placeholder pseudo-element to adjust the color and style of the placeholder text to ensure it is clear and readable; 3. Make the input box responsive and maintain the layout stable by setting box-sizing:border-box and using relative units; 4. Use native controls to hide native controls and combine pseudo-elements and labels to achieve custom visual effects; 5. Always pay attention to accessibility and provide visible focus indicators


Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version







