scroll-margin-inline

简写属性 scroll-margin-inline 设置了元素的行向滚动外边距。

尝试一下

属性构成

此属性为下列 CSS 属性的简写属性:

语法

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

/* 全局值 */
scroll-margin-inline: inherit;
scroll-margin-inline: initial;
scroll-margin-inline: revert;
scroll-margin-inline: revert-layer;
scroll-margin-inline: unset;

取值

<length>

滚动容器对应边的外边距。

描述

scroll-margin 值表示定义滚动吸附区域的外边距,此区域用于将此盒吸附至滚动口。滚动吸附区域的确定方法为:取变换后的边框盒,求其矩形包围盒(与滚动容器的坐标空间中的轴对齐),再加上指定的外边距。

形式定义

初始值as each of the properties of the shorthand:
适用元素all elements
是否是继承属性
计算值as each of the properties of the shorthand:
Animation typeby computed value type

形式语法

scroll-margin-inline = 
<length>{1,2}

示例

简单演示

此示例所实现的内容与上述互动示例非常相似,但此处将解释其实现方法。

此处的目标为创建四个横向滚动区块,其中第二个和第三个吸附至指定位置——靠近但不恰好位于每个区块的右侧。

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 #000;
  scroll-snap-type: x mandatory;
}

与滚动吸附相关的主要部分为 overflow-x: scroll——确保内容可滚动且不被隐藏——以及 scroll-snap-type: x mandatory——要求必须沿横轴出现滚动吸附,且滚动总将止于吸附点。

子元素有如下样式:

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

.scroller > div:nth-child(2n) {
  background-color: #fff;
  color: #663399;
}

此处最相关的部分为 scroll-snap-align: end——指定右侧的边(即此情形中沿 x 轴的“末侧”)为吸附点。

最后指定滚动外边距的值,为第二个和第三个子元素指定不同的值:

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

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

这意味着当滚动过中间的子元素后,滚动将吸附至第二个 <div> 行末边的 1rem 外处,及第三个 <div> 行末边的 2rems 外处。

备注: 此处虽然在行向轴(即此情形中的 x 轴)的首侧末侧均设置了 scroll-margin,但真正相关的仅有末侧边。此处若仅在此边上设置滚动外边距,例如 scroll-margin-inline: 0 1remscroll-margin-inline-end: 1rem,则效果相同。

结果

请自行尝试:

规范

Specification
CSS Scroll Snap Module Level 1
# propdef-scroll-margin-inline

浏览器兼容性

BCD tables only load in the browser

参见