[CSS] display grid; を使って最短2行で上下左右中央揃えする方法

CSSで要素を上下左右中央揃えにする方法はいくつかありますが、display: grid; を使えば最短2行で要素の上下左右中央揃えを実現できます。
display: grid; で要素を上下左右中央揃えにする方法
・html
|
1 2 3 4 5 |
<div class="parent"> <div class="content_center"> <p>テキストテキストテキスト</p> </div> </div> |
・css
|
1 2 3 4 |
.content_center { display: grid; place-items: center; } |
・デモ
See the Pen
display: grid;で上下左右中央揃え by mkl may (@mkl-may)
on CodePen.
従来の方法
Flexbox を使う方法だと3行必要でした。
|
1 2 3 4 5 |
.content_center { display: flex; justify-content: center; align-items: center; } |
position を使う方法だと5行必要でした。
|
1 2 3 4 5 6 7 8 9 10 11 |
.parent { position: relative; } .content_center { position: absolute; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; } |
![MARKLEAPS[マークリープス]](https://markleaps.com/blog/wp-content/themes/mkl/images/00_logo.png)