はじめに
あなたは、ウェブサイトをより使いやすく魅力的にするために、ページ内リンクをスムーズにスクロールさせたいと考えたことはありませんか?
この記事では、初心者にもわかりやすいCSSを使ったページ内リンクのスクロール実装方法を紹介します。
それぞれの方法について、作り方、使い方、対処法、サンプルコード、応用例を徹底解説していきます。
●基本的なページ内リンクの作成方法
まずは、基本的なページ内リンクの作成方法を解説します。
- HTMLでリンク先の要素にid属性を付与
- リンク元のaタグに、href属性に「#id」と指定
<!-- リンク元 -->
<a href="#section1">セクション1へ</a>
<!-- リンク先 -->
<section id="section1">
<h2>セクション1</h2>
<p>ここはセクション1の内容です。</p>
</section>
●CSSのscroll-behaviorプロパティを使用
scroll-behaviorプロパティを使って、ページ内リンクをスムーズにスクロールさせる方法です。
○CSSに下記のコードを追加
html {
scroll-behavior: smooth;
}
これで、ページ内リンクがスムーズにスクロールされるようになります。
対処法: scroll-behaviorプロパティが効かない場合は、次のことを確認してください。
- 他のCSSやJavaScriptで上書きされていないか
- ブラウザが対応しているか(古いブラウザでは対応していない場合がある)
応用例: スクロール速度をカスタマイズしたいする場合は、JavaScriptを使用する必要があります。以下のサンプルコードを参考にしてください。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smooth Scroll Example</title>
<style>
html {
scroll-behavior: smooth;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
const links = document.querySelectorAll("a[href^='#']");
const scrollSpeed = 500;
links.forEach(link => {
link.addEventListener("click", function(event) {
event.preventDefault();
const targetId = this.getAttribute("href");
const targetElement = document.querySelector(targetId);
const rectTop = targetElement.getBoundingClientRect().top;
const scrollTop = window.pageYOffset;
const targetPosition = rectTop + scrollTop;
const startPosition = window.pageYOffset;
const distance = targetPosition - startPosition;
const duration = Math.abs(distance) < 1000 ? scrollSpeed : scrollSpeed * Math.abs(distance) / 1000;
let startTime = null;
function step(currentTime) {
if (startTime === null) {
startTime = currentTime;
}
const elapsedTime = currentTime - startTime;
const rate = elapsedTime / duration;
if (rate < 1) {
window.scrollTo(0, startPosition + distance * rate);
requestAnimationFrame(step);
} else {
window.scrollTo(0, targetPosition);
}
}
requestAnimationFrame(step);
});
});
});
</script>
</head>
<body>
<nav>
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
<a href="#section3">Section 3</a>
</nav>
<section id="section1">
<h2>Section 1</h2>
<p>Here is the content of section 1.</p>
</section>
<section id="section2">
<h2>Section 2</h2>
<p>Here is the content of section 2.</p>
</section>
<section id="section3">
<h2>Section 3</h2>
<p>Here is the content of section 3.</p>
</section>
</body>
</html>
このサンプルコードでは、ページ内リンクのスクロール速度が一定になるように調整しています。
また、距離が遠いリンクほどスクロール速度が速くなるように設定しています。
まとめ
本記事では、CSSを使ってページ内リンクをスムーズにスクロールさせる方法を紹介しました。
それぞれの方法について、作り方、使い方、対処法、サンプルコード、応用例を徹底解説しました。
これであなたもウェブサイトの使いやすさや魅力を向上させることができるでしょう。