2026年5月20日
2026年5月20日
WordPressでスティッキーヘッダーを実装する方法
はじめに
スティッキーヘッダーは、スクロール時にヘッダーが画面上部に固定される機能です。ユーザーがどこをスクロールしても常にナビゲーションにアクセスできるため、UXが向上します。
症状・原因
- スクロールしてもヘッダーを常に表示したい
- スクロール量に応じてヘッダーのスタイルを変えたい
- スティッキーヘッダーが他の要素に重なってしまう
- モバイルでもヘッダーを固定したい
解決手順
ステップ1:CSSで position: sticky を使う(最もシンプル)
/* style.css */
.site-header {
position: sticky;
top: 0;
z-index: 100;
background: #ffffff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
position: sticky は親要素が overflow: hidden や overflow: auto の場合は機能しません。その場合は position: fixed を使います。
ステップ2:position: fixed でより確実に固定する
/* style.css */
.site-header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 999;
background: #ffffff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
transition: box-shadow 0.3s ease;
}
/* fixed にした分、コンテンツが隠れないよう余白を追加 */
.site-main {
margin-top: 80px; /* ヘッダーの高さに合わせる */
}
ステップ3:スクロールで透明→不透明に変化させる
// js/sticky-header.js
document.addEventListener('DOMContentLoaded', function() {
const header = document.querySelector('.site-header');
if (!header) return;
// 初期スタイル(透明)
header.style.backgroundColor = 'transparent';
header.style.transition = 'background-color 0.3s ease, box-shadow 0.3s ease';
window.addEventListener('scroll', function() {
if (window.scrollY > 100) {
header.style.backgroundColor = '#ffffff';
header.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)';
header.classList.add('is-scrolled');
} else {
header.style.backgroundColor = 'transparent';
header.style.boxShadow = 'none';
header.classList.remove('is-scrolled');
}
}, { passive: true });
});
// functions.php — スクリプトをエンキュー
add_action('wp_enqueue_scripts', function(): void {
wp_enqueue_script(
'sticky-header',
get_template_directory_uri() . '/js/sticky-header.js',
[],
filemtime(get_template_directory() . '/js/sticky-header.js'),
true
);
});
ステップ4:管理バーとの干渉を回避する
/* style.css — ログイン中は管理バー分(32px)ずらす */
.admin-bar .site-header {
top: 32px;
}
@media screen and (max-width: 782px) {
.admin-bar .site-header {
top: 46px; /* モバイルの管理バーは46px */
}
}
ステップ5:スクロールダウンで非表示、アップで再表示
// js/sticky-header.js — スクロール方向を検知
let lastScrollY = 0;
const header = document.querySelector('.site-header');
window.addEventListener('scroll', function() {
const currentScrollY = window.scrollY;
if (currentScrollY > lastScrollY && currentScrollY > 200) {
// スクロールダウン → 非表示
header.style.transform = 'translateY(-100%)';
} else {
// スクロールアップ → 表示
header.style.transform = 'translateY(0)';
}
lastScrollY = currentScrollY;
}, { passive: true });
.site-header {
transition: transform 0.3s ease;
}
注意事項
position: fixedを使う場合は、コンテンツが隠れないようbodyや.site-mainにヘッダーと同じ高さのpadding-topまたはmargin-topを設定してください- WordPress管理バーが表示される場合(ログイン中)、
topの値が管理バーの高さ(32px/46px)分ずれます。.admin-barセレクタで調整してください scrollイベントは頻繁に発火するため、{ passive: true }オプションを必ず付けてパフォーマンスを確保してください
まとめ
最もシンプルな方法は position: sticky; top: 0 のCSSのみです。スクロール量に応じたスタイル変更が必要な場合は scroll イベント + クラス切り替えを使います。WordPress管理バーとの干渉は .admin-bar .site-header { top: 32px } で回避できます。