DevToolBox

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

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-contentalign-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

関連ガイド / Related guides