LoginSignup
37
25

More than 3 years have passed since last update.

Flexboxで縦並びかつ左右中央揃えがうまくいかない理由と対策

Posted at

ポートフォリオ作成のため久しぶりにCSSを触って、思うようにいかなかったので解決方法を共有します!

Flexboxで縦並びかつ左右中央にする

要素を縦並びかつ左右中央揃えにしたいな〜
「よし!Flexboxを使おう!」

ということで、
要素を縦並びにするのは flex-direction: column
要素を左右中央揃えにするには justify-content: center

HTMLはこんな感じ
index.html
<main>
    <div class="main-box">
      <h1>タイトル</h1>
      <p>pタグです</p>
    </div>
  </main>

早速やってみる!

style.css
.main-box {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

スクリーンショット 2020-10-08 23.23.02.png

あれ?あれれ?
左右中央にならない...

なぜ左右が中央にならないのか

ググってみたら発見した!

参照:https://baqamore.hatenablog.com/entry/2018/02/14/220836

この記事を書いた人曰く、縦並びにするということは、
スクリーンショット 2020-10-08 23.51.50.png
こういうことだそうだ!

解決方法

ということは左右を中央に寄せたいならば、
justify-content: centerをalign-items:centerに変えれば......

style.css
.main-box {
  display: flex;
  flex-direction: column;
  align-items: center;
}

スクリーンショット 2020-10-08 23.56.38.png

できた!!

37
25
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
37
25