LoginSignup
104
80

More than 5 years have passed since last update.

ブロック内でブロック要素を上下左右中央揃えにする技

Last updated at Posted at 2016-08-06

ブロックの中でブロックを上下左右中央にする簡単な方法

意外と上下左右中央に配置するのは大変

index.html
<div class="wrapper">
    <p>この要素を上下左右中央に寄せたい</p>
</div>

左右中央に寄せるのはとても簡単

index.css
.wrapper {
    text-align: center;
}

上下がなかなか難しい。

index.css
.wrapper {
    postion: relative;
}
.wrapper p {
    position: relative;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: 0 auto;
    height: 50px;
    width: 50px;
}

ざっとこれだけの記述が必要になるし、heightwidthの記述が必要になって、要素の大きさによって完全に中央による保証がない。

flex boxを使ってみる

flex boxに関する詳しい説明はこちら

flex boxの左右中央寄せと上下中央寄せを同時に使ってみる

index.html
<div class="wrapper">
    <p>この要素を上下左右中央に寄せたい</p>
</div>
index.css
.wrapper {
    display: flex;
    justify-content: center; /*左右中央揃え*/
    align-items: center;     /*上下中央揃え*/
}

これだけでブロックの中のブロック要素が上下左右中央に配置される。

104
80
1

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
104
80