LoginSignup
1
0

CSS の色々な「上下左右の中央揃え」を試してみた

Last updated at Posted at 2023-12-05

CSS で上下左右の中央揃えをする際、ブロック要素を対象とするのであれば Flexbox を利用して display: flex; justify-content: center; align-items: center; での中央寄せ方法がメジャーだと思います。

Flexbox を活用した上下左右の揃え方

See the Pen Untitled by Masahiro (@masahiro111) on CodePen.

上記のように簡単に上下左右の中央揃えを実現することができます。しかし、それ以外の方法もありまして、CSS の知識を深めるためにも、上記の例以外で上下左右中央揃えをする方法をご紹介したいと思います。

display:flex;margin:auto; で中央揃え

See the Pen Untitled by Masahiro (@masahiro111) on CodePen.

中央揃えをしたいブロック要素に margin:auto; を指定し、加えてその display:flex; を指定する方法でも上下左右のセンタリングが可能です。

display:grid; で中央揃え

中央揃えをしたいブロック要素の親に display:grid; を指定して、中央に揃えたいブロック要素に place-self:center; を指定することで真ん中に配置することもできます。

See the Pen Untitled by Masahiro (@masahiro111) on CodePen.

この display:grid; は、中央揃えをしたい要素が複数ある場合、以下の例のように display:grid; place-content:center; を一緒に指定すると真ん中に寄るように配置することもできます。

See the Pen grid place-content by Masahiro (@masahiro111) on CodePen.

position:absolute; で中央揃え

中央揃えをしたい要素に position:absolute; inset:50%; translate:-50% -50%; を指定し、その親要素に position: relative; を指定します。

See the Pen Untitled by Masahiro (@masahiro111) on CodePen.


このように「上下左右の中央揃え」を実現する方法は複数あるのでコーディングの際はケースバイケースで使い分けて試してみると良いかもしれません。

参考 URL: https://www.youtube.com/shorts/7I6pb2MHRQg

1
0
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
1
0