CSSで上下左右ド真ん中に配置

CSSで上下左右ド真ん中に配置
Image by janrye from Pixabay

2020.12.04(更新日:2021.03.22)

親要素の上下左右ド真ん中に子要素を配置したい時は多々ある。それぞれ幅や高さが決まっていれば中央配置はmarginなど駆使しても何とかなりそうだけど、現在主流のレスポンシブデザインなど幅が可変場合はなかなかそうは行かない。
そんな時に使えるcssを紹介。構造に合わせて良きものを選択してみよう。

この記事は1年以上経過しています。内容的に古い場合があります。

position + transform

オールラウンダー的に使うならこれ。

/* 親要素(この要素のド真ん中に配置) */
.parent { 
  height: 500px; /* 高さは必須 */
  position: relative; 
}

/* 中央に配置したい子要素 */
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
}

positionで中央に配置したい子要素の左上角を中央に持っていく。次にtransformで子要素の幅と高さそれぞれ半分戻す…と言う仕組み。ただし子要素内がテキストなどインライン系のものだと子要素の幅が安定しない。
例えばメインタイトルを中央にしたが、変なところで改行されたりとか。その場合は子要素に幅を指定。
幅を入れることにより、親要素目一杯ではなく左右に若干の余白も作れる。

/* 親要素(この要素のド真ん中に配置) */
.parent { position: relative; }

/* 中央に配置したい子要素 */
.child {
  width: 80%; /* 左右に10%づつ余白 */
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
}

flexbox

何はなくともflexbox。現在(2020.12)ベンダープレフィックスが必要なので、てんこ盛りに見える。
必要なのは「justify-content/align-items/flex-direction」だけなんだけどなぁ。

/* 親要素に指定するだけ */
.parent {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
}

現在(2020.12)ではほとんどのブラウザで使用出来るけど、念のためベンダープレフィックスは追加した方が無難。