LoginSignup
1
1

More than 5 years have passed since last update.

HTML,CSSでブロック要素の内容を横、縦ともに中央に表示する方法

Posted at

中央に寄せる方法

たくさんの方法があると思いますが、今回はdisplay:tableを使います。

まずこんなものを用意します。

HTML

<div class="center">
  <h1>Hello World</h1>
</div>

CSS

.center{
  wihth:500px;
  height:500px;
}

h1{
  width:500px;
  height:200px;
}

これだと、h1内のテキストは左端に寄り、しかも.centerの上を基準にピッタリとh1がくっついちゃいます。

これくらいのコードだとピクセル指定や、marginで指定してあげてもいいのですが、大きくなると結構困るときが多くなります。

横方向のセンタリング

いわずもがなtext-align:centerです。
CSSに追加してあげましょう。

縦方向のセンタリング

本題です。

要素をテーブルと同じように扱って、縦方向にセンタリングします。

CSS

.center{
  wihth:500px;
  height:500px;
  text-align:center;
  display:table;
}

h1{
  width:500px;
  height:200px;
  display:table-cell;
  vertical-align: middle;
}

どうでしょうか。
これで縦方向にもセンタリングできます。
しかもh1タグごとセンタリングされるので、大きく画面中央に表示してあげたい時なんかは役立つと思います。

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