实现方式
CSS 吸附效果使用 scroll-snap 属性来控制滚动时元素如何对齐。这种效果可以在水平或垂直滚动容器中使用,并且非常适合制作具有滑动效果的内容区域,例如图像画廊或分页组件。
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Dynamic Image Patterns</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="container">
      <div class="item item-1">1</div>
      <div class="item item-2">2</div>
      <div class="item item-3">3</div>
      <div class="item item-4">4</div>
    </div>
  </body>
</html>
.container {
  display: flex;
  height: 300px;
  overflow-x: scroll;
  scroll-snap-type: x mandatory;
}
.container::-webkit-scrollbar {
  width: 0;
}
.item {
  width: 100%;
  height: 100%;
  flex-shrink: 0;
  scroll-snap-align: center; /* 元素中心对齐 */
  scroll-snap-stop: always; /* 强制停留在吸附点 */
}
.item-1 {
  background: lightgrey;
}
.item-2 {
  background: lightpink;
}
.item-3 {
  background: lightblue;
}
.item-4 {
  background: lightgreen;
}

Scroll-snap 属性扩展
1. scroll-snap-type
- 
定义:指定滚动容器的吸附行为。
 - 
语法:
scroll-snap-type: <axis> <mandatory | optional>; - 
属性值:
<axis>:x、y或block、inline。指定滚动的方向(水平、垂直或块级、内联)。<mandatory | optional>:mandatory表示强制对齐到最近的吸附点,optional表示可选对齐。
 - 
示例:
.container { scroll-snap-type: y mandatory; /* 垂直方向强制对齐 */ } 
2. scroll-snap-align
- 
定义:设置滚动容器内的子元素如何对齐到吸附点。
 - 
语法:
scroll-snap-align: <start | end | center> [<start | end | center>]; - 
属性值:
start:元素的开始部分对齐到容器的边界。end:元素的结束部分对齐到容器的边界。center:元素的中心对齐到容器的边界。
 - 
示例:
.item { scroll-snap-align: center; /* 元素中心对齐 */ } 
3. scroll-snap-stop
- 
定义:控制在滚动时元素是否始终会停留在吸附点。
 - 
语法:
scroll-snap-stop: <normal | always>; - 
属性值:
normal:默认值,元素在滚动时不会强制停留在吸附点。always:确保元素始终会停留在吸附点,无论用户滚动多快。
 - 
示例:
.item { scroll-snap-stop: always; /* 强制停留在吸附点 */ }