10
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ひとりCSSAdvent Calendar 2022

Day 13

scroll-marginとscroll-paddingを使ってみる

Last updated at Posted at 2022-12-12

ひとりCSS Advent Calendar 2022 13日目です。

scroll-marginとscroll-paddingを使ってみます。

どんなときに便利か

  • たとえばページ上部にヘッダーを固定させて、ページ内スクロールを実装したとき
    • margin padding だとスクロールさせたときにヘッダーとかぶる
      • 頻繁に遭遇する(またか〜…みたいな。)
      • 考慮するの結構面倒だった
    • scroll-padding を使うとヘッダー分の高さを考慮できる
  • scroll-margin より scroll-padding のほうが使うことが多そう

作ってみる

<header>
  <nav>
    <a href="#1">section1</a>
    <a href="#2">section2</a>
    <a href="#3">section3</a>
    <a href="#4">section4</a>
  </nav>
</header>
<main>
  <section id="1">
    <h2>Headline1</h2>
    <p>Paragraph</p>
  </section>
  <section id="2">
    <h2>Headline2</h2>
    <p>Paragraph</p>
  </section>
  <section id="3">
    <h2>Headline3</h2>
    <p>Paragraph</p>
  </section>
  <section id="4">
    <h2>Headline4</h2>
    <p>Paragraph</p>
  </section>
</main>
html {
  scroll-behavior: smooth;
  scroll-padding-top: 64px;
}

header {
  position: fixed;
  left: 0;
  right: 0;
  height: 56px;
  background: #fff;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: center;
  align-items: center;
}

main {
  padding: 64px 0;
}

section {
  height: 200vh;

}

gif.gif

感想

  • 便利〜!

参考

10
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?