LoginSignup
1
2

More than 3 years have passed since last update.

ヘッダーをposition: fixed;で固定した時のアンカーリンクずれ解消法とoverflow: hidden;

Last updated at Posted at 2019-09-19

概要

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.


参考サイト

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2