できない.dev

CSSで要素を中央に配置するには

flexbox の justify-content と align-items を使い、子要素を親要素の上下左右の中央に配置する基本形を示す。

公開:

プレビュー
<style>
.center-box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 120px;
  background: #f1f5f9;
  border-radius: 8px;
}
.center-item {
  padding: 8px 16px;
  background: #10b981;
  color: #fff;
  border-radius: 6px;
  font-family: system-ui;
}
</style>
<div class="center-box"><span class="center-item">中央</span></div>

display: flex を指定した親要素へ、justify-content で横方向、align-items で縦方向の中央揃えを指定する。
この2つを組み合わせると、子要素の大きさが変わっても上下左右の中央を保てる。

つまずき

align-items による縦方向の中央寄せは、親要素に height か min-height が無いと効かない。
親の高さが内容ぶんに縮むと、縦方向に中央寄せするための余白が生まれないためである。
縦のセンタリングが効かないときは、まず親要素に高さが指定されているかを確認するとよい。