LoginSignup
1
0

More than 1 year has passed since last update.

【備忘録】CSSで上下左右中央寄せ

Posted at

この記事について

CSSで要素を上下左右中央に寄せて配置する方法を毎回ググってる&方法がバラバラになっていたので、メモを残しておく。

基本的なやり方

親に以下を指定する。これだけ。

  • display: flex
  • justify-content: center (左右中央)
  • align-items: center (上下中央)
index.html
<body>
  <div class="parent">
    <p>あいうえお</p>
    <p>かきくけこ</p>
    <p>さしすせそ</p>
  </div>
</body>
<style>
  .parent {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
    background-color: gray;
  }
  p {
    width: 150px;
    background-color: pink;
    margin: 5px;
  }
</style>

見た目はこんな感じになる。
スクリーンショット 2022-03-24 2.14.36.png

縦並びを維持したまま上下左右中央寄せする

pタグ3つをさらにdivタグで囲んでdisplay: flexが効く子要素を1つにすればOK

index.html
<body>
  <div class="content">
    <div>
      <p>あいうえお</p>
      <p>かきくけこ</p>
      <p>さしすせそ</p>
    </div>
  </div>
</body>
<style>
  .content {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
    background-color: gray;
  }
  p {
    width: 150px;
    background-color: pink;
    margin: 5px;
  }
</style>

見た目はこんな感じになる。
スクリーンショット 2022-03-24 2.18.04.png

flex-directionを指定する

flex-directionを親に指定することで、display: flex使用時の子要素の並び方を変更できる。
1つ前のやつと違って、divタグを追加する必要がないので、階層が余計に深くならずに済む。

index.html
<body>
  <div class="parent">
    <p>あいうえお</p>
    <p>かきくけこ</p>
    <p>さしすせそ</p>
  </div>
</body>
<style>
  .parent {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 300px;
    background-color: gray;
  }
  p {
    width: 150px;
    background-color: pink;
    margin: 5px;
  }
</style>

見た目は1つ前のやつと同じになる。
スクリーンショット 2022-03-24 2.18.04.png

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