Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8764

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

$
0
0
この記事について 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> 見た目はこんな感じになる。 縦並びを維持したまま上下左右中央寄せする 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> 見た目はこんな感じになる。 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つ前のやつと同じになる。

Viewing all articles
Browse latest Browse all 8764

Trending Articles