2
2

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 3 years have passed since last update.

「scroll-snap」ちょっとのスクロールで勝手にスクロール位置をコンテンツに合わせてくれるやつ

Posted at

どうも7noteです。画面スクロールをスライドショーみたいにちょうどいい感じの位置まで勝手にスクロールしてくれるアレ(スクロールスナップ)です。

語彙力なさすぎて悲しいのですが、コンテンツに合わせてスクロール位置を自動調整してくれるプロパティ「scroll-snap」を紹介しようと思います。
日本語でも普通にスクロールスナップと呼ぶのが一般的なんですかね、おそらく。

sample.gif

(軽いスクロールだけで自動的にコンテンツに合わせてくれる)

以前からあったようなのですがほぼすべてのブラウザに対応しているそうなので、採用してみようと思い調べてみることに。まぁ最悪スクロールの加減が変わるだけなので効かないブラウザがあってもそこまで大きな影響にはならなさそうですね。

使い方

index.html
<div class="box">
  <section>1</section>
  <section>2</section>
  <section>3</section>
  <section>4</section>
  <section>5</section>
</div>
style.css
.box {
  width: 200px;  /* 適度な幅を指定 */
  height: 200px; /* 適度な高さを指定 */
  scroll-snap-type: y mandatory; /* スクロールスナップの指定 */
  overflow: scroll;              /* はみ出た部分をスクロールできる要素にする */
}

.box section {
  scroll-snap-align: start; /* スクロールスナップの指定 */
  width: 200px;  /* 適度な幅を指定 */
  height: 200px; /* 適度な高さを指定 */
  text-align: center; /* 文字を左右中央にするため */
  line-height: 200px; /* 文字を上下中央にするため */
}

.box section:nth-of-type(even) {
  background: #ccc; /* 偶数番の背景色 */
}
.box section:nth-of-type(odd) {
  background: #aaa; /* 奇数番の背景色 */
}

sample.gif

まとめ

他にも横方向用や、コンテンツとコンテンツの間でスクロールを止められるような設定など細かい設定ができますが、一番良く使われやすそうなものを紹介しました。

さらにくわしく知りたい方は参考サイトへどうぞ!↓

参考:
https://www.mitsue.co.jp/knowledge/blog/frontend/202102/02_1740.html
https://developer.mozilla.org/ja/docs/Web/CSS/scroll-snap-type

おそまつ!

~ Qiitaで毎日投稿中!! ~
【初心者向け】WEB制作のちょいテク詰め合わせ

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?