アトリエロワ

headerを固定した時のページ内リンク。Chrome、Firefox、Safari対応

HTML CSS。headerを固定した時のページ内リンク。Chrome、Firefox、Safari対応

headerを固定した時のページ内リンク

HTML

<a href="#release">ここをクリックでID releaseにページ内リンク</a>
<div id="release" class="pagelink">ここにジャンプしたい</div>

方法1:scroll-margin-top: 100px;

【注意】javascriptでページスムーズスクロールを記述している場合は、この方法では効かないことがある。
そのためhtmlでスムーズスクロールを設定し直す。

html {
  scroll-behavior: smooth;
}
.page-link {
  scroll-margin-top: 100px;
}

chromeの対応:jsに記載

同ページ内でのページ内スクロールは上記でできるが、他のページから飛んできた時にずれる場合

window.onload = function() {
  const header = document.querySelector('header'); // 固定ヘッダー
  const headerHeight = header ? header.offsetHeight : 0;

  if (window.location.hash) {
    const targetId = window.location.hash.replace('#', '');
    const target = document.getElementById(targetId);
    if (target) {
      const top = target.getBoundingClientRect().top + window.pageYOffset - headerHeight;
      window.scrollTo({ top: top, behavior: 'smooth' });
    }
  }
};

方法2:css

古いやり方なので今は使わない

.pagelink {
  padding-top: 100px;
  margin-top: -100px;
  position: relative;
  z-index: 1;
  display: block;
}

HOME > html+css > headerを固定した時のページ内リンク。Chrome、Firefox、Safari対応

html+css

html+css