LoginSignup
23
22

More than 5 years have passed since last update.

flexboxを用いた中央寄せ

Last updated at Posted at 2014-11-29

ドメインが失効してしまったのでこちらで書きます\(^o^)/

天地中央寄せでレイアウトする箇所が出てきたとき、

.parent {
    position: relative;
    width: 100%;
    height: 400px;
}

.child {
    position: absolute;
    width: 300px;
    height: 200px;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(-50%);
}

ってやるのが(IE9以降は)一番簡単だと思っていたのですが、
flexboxを用いるともっと簡単に中央寄せできることを知りました。

flexboxによる中央寄せ

kobito.1417253085.948391.png

.parent {
    display: flex;
    width: 100%;
    height: 400px;
}

.child {
    margin: auto;
    width: 300px;
    height: 200px;
}

ブラウザ対応状況

kobito.1417253636.761631.png
(caniuse参照)

IEは10以降からになってしまいますが、IEとAndroidの状況によっては使えるかもしれませんね。
(なんだかんだでdisplay:table最強伝説となってしまいますが)

参照元

Smashing Magazineからのツイートから拝借

また、IE10のハック的なものもツイートされていました

23
22
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
23
22