試一試
scroll-margin: 0;
scroll-margin: 20px;
scroll-margin: 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 .info {
inline-size: 100%;
padding: 0.5em 0;
font-size: 90%;
writing-mode: vertical-rl;
}
.scroller {
text-align: left;
height: 250px;
width: 270px;
overflow-y: scroll;
display: flex;
flex-direction: column;
box-sizing: border-box;
border: 1px solid black;
scroll-snap-type: y mandatory;
}
.scroller > div {
flex: 0 0 250px;
background-color: rebeccapurple;
color: white;
font-size: 30px;
display: flex;
align-items: center;
justify-content: center;
scroll-snap-align: start;
}
.scroller > div:nth-child(even) {
background-color: white;
color: rebeccapurple;
}
構成屬性
此屬性是以下 CSS 屬性的簡寫:
語法
/* <length> values */
scroll-margin: 10px;
scroll-margin: 1em 0.5em 1em 1em;
/* Global values */
scroll-margin: inherit;
scroll-margin: initial;
scroll-margin: revert;
scroll-margin: revert-layer;
scroll-margin: unset;
值
<length>-
從滾動容器的相應邊緣向外擴充套件的距離。
描述
你可以透過滾動到示例內容兩個“頁面”之間的一部分來檢視 scroll-margin 的效果。為 scroll-margin 指定的值決定了主要位於 吸附視口 之外的頁面部分應保持可見的程度。
因此,scroll-margin 值表示定義滾動吸附區域的向外擴充套件,該區域用於將此框吸附到吸附視口。滾動吸附區域是透過獲取變換後的邊框,找到其矩形邊界框(在滾動容器的座標空間中軸對齊),然後新增指定的向外擴充套件來確定的。
正式定義
| 初始值 | 作為簡寫中的每個屬性 |
|---|---|
| 應用於 | 所有元素 |
| 繼承性 | 否 |
| 計算值 | 作為簡寫中的每個屬性
|
| 動畫型別 | 按計算值型別 |
正式語法
scroll-margin =
<length>{1,4}
示例
基本演示
此示例實現了與上述互動式示例非常相似的功能,不同之處在於我們將在此處向您解釋其實現方式。
這裡的目標是建立四個水平滾動的塊,其中第二個和第三個塊會吸附到位,靠近但不完全在每個塊的左側。
HTML
HTML 包含一個帶有四個子元素的滾動器
<div class="scroller">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
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,它規定滾動吸附必須沿水平軸發生,並且滾動將始終停在吸附點上。
子元素的樣式如下
.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: start;
}
.scroller > div:nth-child(2n) {
background-color: white;
color: rebeccapurple;
}
這裡最相關的部分是 scroll-snap-align: start,它指定左側邊緣(在我們的例子中是沿 x 軸的“起點”)是指定的吸附點。
最後,我們為第二個和第三個子元素指定不同的滾動外邊距值
.scroller > div:nth-child(2) {
scroll-margin: 1rem;
}
.scroller > div:nth-child(3) {
scroll-margin: 2rem;
}
這意味著當滾動經過中間的子元素時,滾動將吸附到第二個 <div> 左邊緣以外 1rem,以及第三個 <div> 左邊緣以外 2rem 的位置。
注意:這裡我們一次性設定了所有邊上的 scroll-margin,但只有起始邊緣是真正相關的。這裡只在該邊緣設定滾動外邊距也能很好地工作,例如使用 scroll-margin-inline-start: 1rem 或 scroll-margin: 0 0 0 1rem。
結果
自己嘗試一下
規範
| 規範 |
|---|
| CSS 滾動捕捉模組級別 1 # scroll-margin |
瀏覽器相容性
載入中…