CSS

【CSSのみ】ページ内リンクをスムーズにスクロールさせる

今日は、ページ内リンクをスムーズにスクロールさせます。

CSSだけで実装できるので手軽に使えます。

 

挙動は下記のサンプルをお試しください。

See the Pen
スムーズなリンク
by MacLove (@maclove1)
on CodePen.

このようにスムーズなスクロールが実装できます。

目次
  1. CSS
  2. HTML
  3. CSS

CSS

肝となるCSSはこちら。

html {
    scroll-behavior: smooth;
}

 

htmlタグに scroll-behavior: smooth; をつけます。

 

 

以下全体のサンプルコードです。

HTML

<nav id="nav">
    <a href="#page-1">page1</a>
    <a href="#page-2">page2</a>
    <a href="#page-3">page3</a>
</nav>

<div class="container">
    <div id="page-1" class="contents"><a href=#nav>topへ</a></div>
    <div id="page-2" class="contents"><a href=#nav>topへ</a></div>
    <div id="page-3" class="contents"><a href=#nav>topへ</a></div>
</div>

 

CSS

html {
    scroll-behavior: smooth;
}

a {
    display: inline-block;
    width: 100px;
    text-decoration: none;
}

nav {
    margin: 0 auto;
    text-align: center;
}

.container {
    margin-top: 300px;
}

.contents {
    background-color: pink;
    border: solid 1px white;
    height: 600px;
}