LoginSignup
11
6

More than 3 years have passed since last update.

あまり知られていない(と思う)CSS中央寄せテクニック

Last updated at Posted at 2019-11-30

CSS中央寄せテクニックとして、

position: absolute;
left: 0;
right: 0;
margin: auto;

はあまりにも有名だが、
親要素より大きな要素を中央寄せしようとすると左寄せになってしまう問題がある。

スクリーンショット 2019-11-30 18.31.59.png

この問題を解消するためのCSSの書き方が以下になります。

css
position: absolute;
left: -100%;
right: -100%;
margin: auto;

スクリーンショット 2019-11-30 18.39.28.png
left right は必ずしも -100% でなくてもよい。
厳密には親要素からはみ出した数値の半分をleft right にマイナス値で設定する。
上記の場合だと、

親:400px - 子:600px = -200px
-200px / 2 = -100px
left: -100px; right: -100px

こんなときに使える

コンテナー内にあるセクション要素の背景が、コンテナーを突き抜けてるようなデザインだった場合、いちいちコンテナー内からセクション要素を外に出す必要がなくなる。
スクリーンショット 2019-11-30 20.30.12.png

css
section2 {  
  position: relative;

  &::before {
    content: '';
    display: block;
    position: absolute;
    z-index: -1;
    left: -100%;
    right: -100%;
    margin: auto;
    width: 100vw;
    height: 100%;
    background: url(bg.jpg);
  }
}
11
6
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
11
6