
・CSSを使って上下や左右中央寄せする方法は?
こんな疑問にお答えします。
デザインカンプによっては、上下や左右に中央寄せになっていることありますよね。
コーダーなら一度は実装したことあるはず。
ただ実装方法が色々あり、迷ってしまうんですよね。
そこで今回、中央寄せする方法をまとめてみました。

覚えておくべし!
ということで、この記事では「上下・左右に中央寄せする方法」について解説していきます!
上下・左右に中央寄せする方法
目次
【CSS】上下・左右に中央寄せする方法【Gridなら2行】
上下・左右に中央寄席する方法は主にこちら↓
- 左右:「text-align」
- 左右:「margin」
- 上下:「line-height」
- 上下:「vertical-align」
- 上下左右:「position+margin」
- 上下左右:「position+transform」
- 上下左右:「flex」
- 上下左右:「grid」
順に見ていきましょう。
子要素の文章や画像を、左右中央寄せしたいなら「text-align: center」を使います。

text-align: center;
要素自体を中央寄せしたい場合は、左右のmarginをautoにします。
ただ要素の横幅指定が必要です。(今回は横幅50%に指定)

<div class="box">
<p class="txt">ここに文章が入ります。</p>
</div>
.txt {
width: 50%;
margin-right: auto;
margin-left: auto;
}
「line-height」を使い、縦長さと行間を等しくすることで上下中央寄せが可能です。

<div class="box">
<p class="txt">ここに文章が入ります。</p>
</div>
.box {
height: 100px;
}
.txt {
line-height: 100px;
}
ただし「高さが決まっている」+「テキストが1行のみ」のときしか、有効な方法ではありません。
「vertical-align:middle」を使うことで、上下中央寄せが可能です。

<div class="box">
<p class="txt">ここに文章が入ります。</p>
</div>
.box {
display: table;
}
.txt {
display: table-cell;
vertical-align: middle;
}
ただし「vertical-align」が効くのは、インライン要素またはテーブルセルです。
そのため「display: table-cell;」を指定して、効くように指定しています。
「position: absolute」と「margin」の特性を生かして、上下左右中央寄せすることが可能です。

<div class="box">
<p class="txt">ここに文章が入ります。</p>
</div>
.box {
height: 300px;
position: relative;
}
.txt {
width: 50%;
height: 50px;
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
margin: auto;
}
要素の高さを指定する必要があるのがデメリットですね。
これは結構主流ではないでしょうか。
「absolute」と「transform」を用いて上下左右中央寄せする方法です。

<div class="box">
<p class="txt">ここに文章が入ります。</p>
</div>
.box {
height: 300px;
position: relative;
}
.txt {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
中の要素の縦幅を指定する必要がないのが良いですね。
レスポンシブ対応もしやすいです。
シンプルでかなり楽なやり方です。
「display: flex」+「justify-content: center」+「align-items: center」を用いて上下左右中央寄せする方法。

<div class="box">
<p class="txt">ここに文章が入ります。</p>
</div>
.box {
display: flex;
justify-content: center;
align-items: center;
}
これは最新、かつ最短コードでできる上下左右中央寄せです。
「display: grid」+「place-items: center」のたった2行を使うだけ。

<div class="box">
<p class="txt">ここに文章が入ります。</p>
</div>
.box {
display: grid;
place-items: center;
}
「place-items」を使うことで、本来2行必要なコードを1行にまとめることができます。
place-items: center;
// ↓
justify-items: center;
align-items: center;
【最新】CSSで上下・左右に中央寄せする方法8選【Gridなら2行】:まとめ
- 左右:「text-align」
- 左右:「margin」
- 上下:「line-height」
- 上下:「vertical-align」
- 上下左右:「position+margin」
- 上下左右:「position+transform」
- 上下左右:「flex」
- 上下左右:「grid」

中央寄せしたい場合は試してみてね!