CSS - scroll-padding-*
概要
| 属性名 |
scroll-padding-top scroll-padding-bottom scroll-padding-right scroll-padding-left |
|---|---|
| 値 | auto | <length> | <percentage> |
| 初期値 | auto |
| 適用可能要素 | スクロールコンテナ |
| 継承 | しない |
| サポート | https://caniuse.com/?search=scroll-padding-top |
説明
ページ内のアンカーに移動する際や、scroll-snap-type でスクロールスナップする際に、スクロール位置を指定した長さだけずらします。ページ上部に固定ヘッダを表示している場合にスクロールした箇所がヘッダの下に隠れてしまうのを防ぐ場合などに有効です。scroll-padding-* はスクロールコンテナ(親要素)に、scroll-margin-* はスクロールコンテンツ(子要素)に指定する点が異なります。
| 値 | 説明 |
|---|---|
| auto | 自動的に調整されます。 |
| <length> | マージンを指定します。 |
使用例
CSS
:root {
--header-height: 2.5rem;
}
.page {
position: relative;
border: 1px solid #999;
height: 10rem;
overflow-y: scroll;
overflow-x: hidden;
scroll-behavior: smooth;
scroll-padding-top: var(--header-height);
}
header {
position: sticky;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, .5);
color: white;
height: var(--header-height);
line-height: var(--header-height);
width: 100%;
padding-left: .5rem;
}
main {
position: absolute;
top: 0;
left: 0;
overflow-y: scroll;
width: 100%;
padding-top: var(--header-height);
}
.my-section {
height: 30rem;
}
h1 {
margin-top: 0;
}
HTML
<div class="page">
<header>Header</header>
<main>
<section>
<h2 id="section-1">Section-1</h2>
<ul>
<li><a href="#section-2">Section-2</a>
<li><a href="#section-3">Section-3</a>
</ul>
</section>
<section>
<h2 id="section-2">Section-2</h2>
<ul>
<li><a href="#section-1">Section-1</a>
<li><a href="#section-3">Section-3</a>
</ul>
</section>
<section>
<h2 id="section-3">Section-3</h2>
<ul>
<li><a href="#section-1">Section-1</a>
<li><a href="#section-2">Section-2</a>
</ul>
</section>
</main>
</div>
表示
関連項目
scroll-margin-*リンク
- https://developer.mozilla.org/ja/docs/Web/CSS/scroll-padding-top
- https://drafts.csswg.org/css-scroll-snap/#padding-longhands-physical
Copyright (C) 2022 杜甫々
初版:2022年8月14日、最終更新:2022年8月21日
https://www.tohoho-web.com/css/prop/scroll-padding-x.htm