flex item は幅を指定せずに margin: auto で縦横中央揃えできる
margin: auto
を使用した縦横中央揃えは要素自体に幅((max-)width, (max-height)
)の指定が必須と思っていた。
例えば、position: absolute
と組み合わせた以下の要素は親(absolute
の基準)に対して縦横中央揃えされるが
.test { background-color: aqua; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; max-height: 100px; max-width: 100px; }
これは max-width
と max-height
の指定がない場合は動作しない。
しかし、flex item (flex box の子要素) の場合はなぜか幅の指定がなくても縦横中央揃え可能になる。
.parent { display: flex; } .test { background-color: aqua; margin: auto; }
<div class="parent"> <div class="test">hoge</div> </div>
これは幅の指定の有無以外は、最初のコード例と同一になるので、親の大きさに合わせて縦横中央揃え可能になる。
こうすれば 500px の正方形の中で縦横中央揃えになる
.parent { display: flex; width: 500px; height: 500px; } .test { background-color: aqua; margin: auto; }
画面全体に対して縦横中央揃えする場合は、親自体を広げれば OK
.parent { display: flex; position: absolute; top: 0; left: 0; right: 0; bottom: 0; }
ちなみに、margin: auto
を使わずにこの指定でも問題ない
.parent { display: flex; justify-content: center; align-items: center; }
どちらがベストなのかは分からない。参考リンク↓