LoginSignup
2

More than 5 years have passed since last update.

ブロック要素と文字の中央寄せは、違うんだぜ!

Posted at

中央寄せとは言っても、適用したい要素によって方法が違う。うっかりブロック要素と文字への中央寄せを勘違いしたことがあったので、メモする。

ブロック要素の中央寄せ

margin: 0 auto; を使う。

index.html

<div class="box1">
<div class="box2">
</div>
</div>

style.css

.box1{
  width: 450px;
  background-color: red;
}

.box2{
  width: 150px;
  height:450px;
  background-color: blue;
  margin: 0 auto;
}

margin: 0 auto; とすることで、子要素は親要素に対し、上下には要素間の距離をとらない。また左右にはautoが効き、等間隔の距離をとり、結果的に中央揃いになる。

親要素の横幅は450px, 子要素は150pxなので、左右の余白は(450-150)/2 = 150pxとなる。

テキストの中央寄せ

text-aline: centerを使うだけ。

以上

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
2