この記事について
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>