0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【モダンなCSS】要素を中央に配置しよう

0
Posted at

CSSの中央揃えにはさまざまな方法がありますが、今回はその中でもモダンな2つの手法に絞って解説します。

1. Gridを使う

grid属性で中央揃えをする方法です。以下の2行で実装できるので、便利です。

.card {
 display: grid;
 place-item: center;
}

例)

See the Pen Grid Center by Kariu (@kariray) on CodePen.

2. position:absolute + inset:0 + margin: auto

insetはcssでtop,right,bottom.leftを一気に指定できるショートハンド(略記)です。
要素にposition: absolute;inset: 0;そしてmargin: auto;を指定することで簡単に中央寄せにできます。

/* 親コンテナ*/
.parent {
 position: relative;
}

/* 要素 */
.element {
 position: absolute;
 inset: 0;
 margin: auto;
 
 width: 300px;
 height: 300px;
}

ざっくり説明

  • inset: 0; で「全方向」に引っ張る
    • これにより、要素は親要素の「上下左右すべての端に、距離0まで引き伸ばそうとする力」がかかった状態になる
  • margin: auto; で余白を均等に分配する
    1. 要素には「全方向に広がりたい」という力がかかっている
    2. 要素に widthheightが決まっている場合、それ以上は広がれない
    3. 余ったスペースが上下左右で均等に計算され、結果として中央に配置される

注意点
中央に寄せたい要素に必ず widthheightなどのサイズを指定してください。
(サイズが決まっていないと要素が親いっぱい広がってしまうため)

例)

See the Pen absolute+inset Center by Kariu (@kariray) on CodePen.

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?