概要
position: fixed;で画面上部にヘッダーを固定した場合の
アンカーリンクのズレを直す方法として以下を試しましたが、
親要素にoverflow: hidden;が設定されているとChromeで効かなくなることに気づかずハマったのでメモ。
試した解消法
パディングとネガティブマージンを使う
See the Pen ヘッダーをposition: fixed;で固定した時のアンカーリンクずれ解消法 by Kai (@kai-ono) on CodePen.
アンカー要素 {
margin-top: -60px;
padding-top: 60px;
}
:target疑似クラスを使う
:target::before {
content: "";
display: block;
height: 50px;
margin-top: -50px;
}
効かなかった方法 (2019/9/19時点)
疑似要素を使う
See the Pen 疑似要素を使ったアンカーずれ解消法サンプル(※効きませんでした) by Kai (@kai-ono) on CodePen.
アンカー要素ID::before {
content: "";
display: inline-block;
height: 50px;
margin-top: -50px;
vertical-align: top;
}
親要素にoverflow: hidden;が入っている
※Chromeで効かなくなります。Safari、Firefoxは大丈夫。
See the Pen
ヘッダーをposition: fixed;で固定した時のアンカーリンクずれ解消法(親要素にoverflow: hidden;があって効かないパターン) by Kai (@kai-ono)
on CodePen.