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

瀏覽器相容性

另見