scroll-margin-inline-end

Baseline 已广泛支持

此功能已成熟,并可在多种设备和浏览器版本上运行。自 2021 年 9 月起,所有浏览器均已支持此功能。

scroll-margin-inline-end 属性定义了用于将此框捕捉到 吸附端口 的内联维度末尾的滚动吸附区域的边距。滚动吸附区域通过获取变换后的边框,找到其矩形边界框(在滚动容器的坐标空间中与轴对齐),然后添加指定的外部偏移量来确定。

试一试

scroll-margin-inline-end: 0;
scroll-margin-inline-end: 20px;
scroll-margin-inline-end: 2em;
<section class="default-example" id="default-example">
  <div class="scroller">
    <div>1</div>
    <div id="example-element">2</div>
    <div>3</div>
  </div>
  <div class="info">Scroll »</div>
</section>
.default-example {
  flex-wrap: wrap;
}

.default-example .info {
  width: 100%;
  padding: 0.5em 0;
  font-size: 90%;
}

.scroller {
  text-align: left;
  width: 250px;
  height: 250px;
  overflow-x: scroll;
  display: flex;
  box-sizing: border-box;
  border: 1px solid black;
  scroll-snap-type: x mandatory;
}

.scroller > div {
  flex: 0 0 250px;
  width: 250px;
  background-color: rebeccapurple;
  color: white;
  font-size: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  scroll-snap-align: end;
}

.scroller > div:nth-child(even) {
  background-color: white;
  color: rebeccapurple;
}

语法

css
/* <length> values */
scroll-margin-inline-end: 10px;
scroll-margin-inline-end: 1em;

/* Global values */
scroll-margin-inline-end: inherit;
scroll-margin-inline-end: initial;
scroll-margin-inline-end: revert;
scroll-margin-inline-end: revert-layer;
scroll-margin-inline-end: unset;

<length>

从滚动容器的内联末端边缘向外的偏移量。

正式定义

初始值0
应用于所有元素
继承性
计算值同指定值
动画类型按计算值类型

正式语法

scroll-margin-inline-end = 
<length>

示例

基本演示

此示例实现了与上述交互式示例非常相似的功能,不同之处在于我们将在此处向您解释其实现方式。

这里的目标是创建四个水平滚动的块,其中第二个和第三个块会吸附到位,靠近但不完全位于每个块的右侧。

HTML

HTML 包含一个带有四个子元素的滚动器

html
<div class="scroller">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

CSS

让我们浏览一下 CSS。外部容器的样式如下

css
.scroller {
  text-align: left;
  width: 250px;
  height: 250px;
  overflow-x: scroll;
  display: flex;
  box-sizing: border-box;
  border: 1px solid black;
  scroll-snap-type: x mandatory;
}

与滚动吸附相关的主要部分是 overflow-x: scroll,它确保内容将滚动而不是被隐藏,以及 scroll-snap-type: x mandatory,它规定滚动吸附必须沿水平轴发生,并且滚动将始终停在吸附点上。

子元素的样式如下

css
.scroller > div {
  flex: 0 0 250px;
  width: 250px;
  background-color: rebeccapurple;
  color: white;
  font-size: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  scroll-snap-align: end;
}

.scroller > div:nth-child(2n) {
  background-color: white;
  color: rebeccapurple;
}

最相关的部分是 scroll-snap-align: end,它指定右侧边缘(在我们的例子中是沿 x 轴的“末端”)是指定的吸附点。

最后,我们为第二个和第三个子元素指定了不同的滚动边距值。

css
.scroller > div:nth-child(2) {
  scroll-margin-inline-end: 1rem;
}

.scroller > div:nth-child(3) {
  scroll-margin-inline-end: 2rem;
}

这意味着当滚动经过中间的子元素时,滚动会吸附到第二个 <div> 的内联末端边缘之外的 1rem 处,以及第三个 <div> 的内联末端边缘之外的 2rems 处。

结果

自己尝试一下

规范

规范
CSS 滚动捕捉模块级别 1
# margin-longhands-logical

浏览器兼容性

另见