中央揃えの手法とその使う場面
1 margin: auto;
何に対してmargin: auto;を適用させるか
中央揃えしたい要素
使う場面
中央揃えしたい要素がブロック要素の時
ただし、この中央揃えしたい要素にはしっかり幅を設定してあげておいてください
See the Pen margin: auto; by Kazuhito Nakayama (@kazuhito-nakayama) on CodePen.
2 text-align: center;
何に対してtext-align: center;を適用させるか
中央揃えしたい要素の親要素
使う場面
中央揃えしたい要素がインライン要素の時
See the Pen inline-textalign by Kazuhito Nakayama (@kazuhito-nakayama) on CodePen.
ただし、インライン要素にdisplay: blockをかけてブロック要素にしてしまう別解もあります
See the Pen inline-to-block by Kazuhito Nakayama (@kazuhito-nakayama) on CodePen.
3 positionプロパティ
何に対してpositionプロパティを適用させるか
中央揃えしたい要素の親要素に
position: relative;
中央揃えしたい要素の親要素に
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
使う場面
中央揃えしたい要素は、ブロック要素でもインライン要素でも使える。
See the Pen position by Kazuhito Nakayama (@kazuhito-nakayama) on CodePen.
author: Kazuhito Nakayama twitter