CSS中央寄せの方法まとめ
CSSの中央寄せは手法が多すぎて迷いがちですが、「何を」「どの方向に」寄せたいかで 正解はほぼ一意に決まります。まず下の早見表で選び、それぞれのコードと 「効かないときの原因」を確認してください。
A decision table for centering in CSS — flexbox, grid place-items, margin auto, text-align — plus the reasons vertical centering silently fails.
TL;DR
- 単一要素の縦横中央:
display: grid; place-items: center;(最短2行) - 複数要素や間隔調整あり:
display: flex; justify-content: center; align-items: center; - 縦中央が効かない原因の9割は「親に高さが無い」。
min-height: 100dvh等を先に確認
1. 早見表 / Decision table
| 寄せたいもの / Target | 方向 / Axis | 推奨 / Use |
|---|---|---|
| テキスト・インライン要素 | 横 | text-align: center(親に指定) |
| 幅のあるブロック要素 | 横 | margin-inline: auto(自身に指定・width必須) |
| 単一の子要素 | 縦横 | display: grid; place-items: center(親に指定) |
| 複数の子要素・間隔調整 | 縦横 | display: flex + justify-content / align-items |
| 重ね表示(モーダル・バッジ) | 縦横 | position: absolute; inset: 0; margin: auto(サイズ指定要) |
| 通常フローのまま(コンテナ不要) | 縦 | align-content: center(2024年〜全ブラウザ対応) |
2. 定番3パターンのコード / The three standard patterns
/* 1. grid: 単一要素の縦横中央(最短) */
.parent {
display: grid;
place-items: center;
min-height: 100dvh; /* 親に高さが必要 */
}
/* 2. flexbox: 複数要素・gap併用 */
.parent {
display: flex;
justify-content: center; /* 主軸(横) */
align-items: center; /* 交差軸(縦) */
gap: 16px;
min-height: 100dvh;
}
/* 3. ブロックの横中央(古典・今も現役) */
.child {
width: min(90%, 640px);
margin-inline: auto;
}flexboxのjustify-contentとalign-itemsの組み合わせはFlexboxジェネレーターで プレビューを見ながら確認できます。gridのプロパティはCSS Gridジェネレーターが対応しています。
3. 「効かない」ときのチェックリスト / When centering fails
| 症状 / Symptom | 原因 / Cause | 対処 / Fix |
|---|---|---|
| 縦中央だけ効かない | 親の高さ=中身の高さになっている | 親に min-height: 100dvh 等を指定 |
margin: auto が効かない | インライン要素 or width未指定 | display: block + width を指定 |
text-align でdivが動かない | text-alignはインライン内容にのみ効く | ブロックには margin-inline: auto |
vertical-align が効かない | inline / table-cell 専用プロパティ | flex か grid に切り替える |
| 100vhでスマホだけずれる | モバイルブラウザのUIバー分 | 100dvh(動的ビューポート)を使う |
4. 新しい選択肢: align-content / The modern block-layout option
/* flexもgridも不要。通常のブロックのまま縦中央(2024年〜Baseline) */
.parent {
align-content: center;
min-height: 100dvh;
}2024年以降の全主要ブラウザで、display を変えずにブロックコンテナへ直接align-content: center が指定できるようになりました。 flex化すると子のmarginの相殺が消える等の副作用が困る場面で便利です。 古いブラウザへの配信が必要な場合はflex/gridを使ってください。
5. English summary
Pick by target and axis: text-align: center for inline content,margin-inline: auto for blocks with a width, display: grid; place-items: centerfor a single child, and flexbox when you have several children or need gap control. Nine times out of ten, "vertical centering doesn't work" means the parent has no height — give itmin-height: 100dvh (dvh avoids the mobile URL-bar offset of 100vh). Since 2024,align-content: center works on plain block containers, centering vertically without switching to flex or grid.
関連ツール / Related tools
- CSS Flexbox Generator - プレビューを見ながらプロパティ確認
- CSS Grid Generator
- CSS Generator(box-shadow / border-radius 等)
- アスペクト比計算機