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?

HTML&CSSで上下左右中央にする方法まとめ

Posted at

はじめに

Web制作をしていると、「要素を上下左右中央に配置したい」という場面はとても多いですよね。しかし、CSSの書き方によってはうまくいかなかったり、ブラウザによって表示がズレたりすることもあります。この記事では、HTMLとCSSを使って、要素を「左右中央」「上下中央」「上下左右中央」に配置する方法を分かりやすく解説します。

左右中央にする方法

要素を左右中央に配置するには、よく使われる方法がいくつかあります。

1. text-align: center; を使う(インライン要素やインラインブロック要素の場合)

index.html
<div style="text-align: center; background-color: lightcoral;">
  <span>中央揃えのテキスト</span>
</div>

image.png

2. margin: 0 auto; を使う(ブロック要素の場合)

index.html
<div style="width: 300px; margin: 0 auto; background-color: bisque;">
  幅が指定されている要素
</div>

image.png

横幅(width)の指定が必要です。

3. Flexboxを使う

index.html
<div style="display: flex; justify-content: center; background-color: bisque;">
  <div>中央揃えの要素</div>
</div>

image.png

上下中央にする方法

上下だけを中央揃えにしたい場合は、Flexboxのalign-itemsが便利です。

1. Flexboxを使う

index.html
<div style="display: flex; flex-direction: column; justify-content: center; height: 300px; background-color: bisque;">
  <div>上下中央揃えの要素</div>
</div>

image.png

親要素に高さ(height)の指定が必要です。

2. Line-heightを使う(テキストのみの場合)

index.html
<div style="height: 100px; line-height: 100px;">
  テキスト上下中央
</div>

image.png

単一行テキストのときのみ有効です。

3. align-itemsを使う

index.html
<div style="display: flex; align-items: center; height: 200px; background-color: lightpink;">
  <div>上下中央揃えの要素</div>
</div>

image.png

上下左右中央にする方法

もっとも実用的なレイアウトです。いくつか方法があります。

1. Flexboxを使う(おすすめ!)

index.html
<div style="display: flex; justify-content: center; align-items: center; height: 300px; background-color: bisque;">
  <div>上下左右中央</div>
</div>

image.png

2. Gridを使う

index.html
<div style="display: grid; place-items: center; height: 300px; background-color: darkseagreen;">
  <div>上下左右中央</div>
</div>

image.png

3. 絶対配置(position: absolute)を使う

index.html
<div style="position: relative; height: 300px; background-color: bisque;">
  <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">
    上下左右中央
  </div>
</div>

image.png

親要素にposition: relative;が必要です。

注意点

  • FlexboxやGridはIE11では一部挙動が異なるため、古いブラウザ対応が必要な場合は注意しましょう
  • 親要素の高さや幅が決まっていないと、上下中央揃えはできません
  • margin: 0 auto;は上下中央にはできません(左右のみ)
  • 複雑なレイアウトの場合はFlexboxかGrid推奨です

最後に

この記事では、HTMLとCSSだけで要素を中央揃えにするさまざまな方法をご紹介しました。レイアウトの基本なので、ぜひ使い分けてみてください!

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?