LoginSignup
38
43

More than 1 year has passed since last update.

【HTML/CSS】モダン中央揃え3選

Last updated at Posted at 2021-05-13

CSSを使ったモダンな要素の中央揃えの手法を3つ紹介します。

忙しい人の為に

See the Pen zYNVRgQ by Yuki Ishii (@yukiishii) on CodePen.

はじめに

中央揃えさせる要素は下記のHTMLのように親要素があり子要素が1つの場合です。
子要素が複数ある場合は予想と違う結果が出る可能性があります。
またテキストやボタンなど行のみを中央揃えしたい場合はまた別の手法が有効となります。

<h1>No centralized</h1>
<div class="container">
  <div class="child">
    Child
  </div>
</div>

image.png

displary: grid; で中央揃え

一番コードが短くてすむ手法です。

.container {
  /*  Following code makes centralizing  */
  display: grid;
  place-items: center;
}

.child {}

image.png

display: flex; で中央揃え

Gridを使用したものより1行コードが増えますが多用されている手法です。

.container {
  /*  Following code makes centralizing  */
  display: flex;
  justify-content: center;
  align-items: center;
}

.child {}

image.png

position: absolute; で中央揃え

先に紹介した手法とは別で子要素自体にスタイリングをしポジションを移動させます。
親要素をposition: relative;にする必要があります。

.container {
  /*  Need parent a relative position  */
  position: relative;
}

.child {
  /*  Following code makes centralizing  */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

image.png

終わりに

今回手段のみを紹介しましたが、理由や仕組みなどは他の記事で紹介したいと思います。
今すぐ気になる方はご連絡ください。

38
43
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
43