中央揃え
2022年3月15日
みなさんこんにちは。
ケミストのWeb担当みやのです。
「Web」記事では、これまでに得たWebに関する知識を記録として残していきたいと思います。
今回は「中央揃え」の方法を調べました。
「中央寄せ」「センタリング」ともいいます。
左右中央揃え
① text-align:center
インライン要素の左右中央揃えにはtext-align:centerを使います。
Bootstrapではtext-centerというクラス名です。
.text-center {
text-align: center;
}
② margin:auto
ブロック要素を左右中央揃えするには、margin-rightとmargin-leftをautoにします。
Bootstrapではmx-autoというクラス名です。
幅が100%ではない画像の中央揃えに使います。
.mx-auto {
margin-right: auto;
margin-left: auto;
}
③ justify-content:center
flexboxを使って中央揃えができます。
display:flexとjustify-content:centerを指定します。
Bootstrapではjustify-content-centerというクラス名です。
ベンダープレフィックスも併記します。
.justify-content-center {
-ms-flex-pack: center;
justify-content: center;
}
上下中央揃え
④ vertical-align:middle
インライン要素どうしの上下中央揃えにはvertical-align:middleを指定します。
Bootstrapではalign-middleというクラス名です。
表(table)の左右の項目の上下中央揃えに使います。
.align-middle {
vertical-align: middle;
}
⑤ align-items:center
flexboxは上下中央揃えもできます。
display:flexとalign-items:centerを指定します。
Bootstrapではalign-items-centerというクラス名です。
ベンダープレフィックスも併記します。
画像と文章を上下中央揃えしたい時に使います。
.align-items-center {
-ms-flex-align: center;
align-items: center;
}
上下左右中央揃え
⑥ position:absolute
ブロック要素の場合、
・親要素にposition:relative
・子要素にposition:absolute
・top、right、bottom、left、width、heightがauto以外
・margin:auto
これらの条件を満たすと上下左右の中央揃えができます。
.parent {
position: relative;
height: 7rem;
}
.child {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 50%;
height: 4rem;
margin: auto;
}
⑦ transform
ブロック要素で、幅や高さを指定したくない場合には
・親要素にposition:relative
・子要素にposition:absolute
・top:50%
・left:50%
・transform:translateY(-50%)
・transform:translateX(-50%)
とすると上下左右の中央揃えができます。
ブロック要素の左上の角を中心に持ってきて、そこから要素の高さの半分だけ上に戻し、幅の半分だけ左に戻す感じです。
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translateY(-50%) translateX(-50%);
transform: translateY(-50%) translateX(-50%);
}
まとめ
もう全部flexboxでいいんじゃないかなと思うのですが、これは素人考えでしょうか。
目標をセンターに入れてスイッチ。