要素中央ぞろえの方法について
ただ中央ぞろえしたい場合
text-align: center;横並びした要素群に対して中央ぞろえしたい場合
例えばこんな状況。
要素内の要素を中央ぞろえしたい場合、class = "title"を、
text-align: center;しても中央によってくれない。
<div class="title">
<div>
<p>Hello,</p>
</div>
<div>
<p>World!</p>
</div>
</div>その場合はjustify-content: center;と記述すると寄ってくれる。
display: flex;
text-align: center;
justify-content: center;そもそも、text-align: center;はインライン要素かブロック要素内のテキストに対してのみ適用されるので、上のような場合は中央揃えがされない。
justify-content: center;はflexコンテナ内で使用でき、横並びになったフレックスアイテムが中央によるという動作をする。
上下中央揃え
css gridを使用する
.container {
display: grid;
place-items: center;
}このplace-items: center;はalign-items: center;とjustify-items: center;を同時に指定できる省略形である。
また、整列させる字句を変えたいなら以下のように記述することもできる。
.container {
display: grid;
align-items: center; /* 垂直方向のみ中央 */
justify-items: start; /* 水平方向は開始位置(左端) */
}