本記事では、display:flexで横並びになったアイテムを縦並びにする方法について解説しています。
HTML/CSSの学習におすすめ参考書
1冊ですべて身につくHTML&CSSとWebデザイン入門講座
先輩くん
Amazon Kindle Unlimitedに登録すると、月額980円で読み放題だからオススメだよ!
後輩ちゃん
初回30日間は無料だから、まだ登録したことのない人はぜひ試してみてね!
綺麗なコードが書けるようになる!
リーダブルコード-より良いコードを書くためのシンプルで実践的なテクニック
先輩くん
より良いコードを書きたい人におすすめの本だよ!
後輩ちゃん
10以上前の書籍ですが、内容は今でも役に立つものばかりです!
flex-directionを使う
結論から申し上げますと、display:flexで横並びになったアイテムを縦並びにするにはflex-directionプロパティにcolumnの値を指定します。
.sample{
display: flex;
flex-direction: column;
}
実践:縦並びにしてみよう
実際に、下記のサンプルコードを使用して縦並びになるか確認しましょう。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="content">
<div class="content__item">Item1</div>
<div class="content__item">Item2</div>
<div class="content__item">Item3</div>
<div class="content__item">Item4</div>
<div class="content__item">Item5</div>
</div>
</body>
</html>
.content {
height: 50vh;
display: flex;
flex-direction: column; /* 横並びのアイテムを縦並びにする */
/* 重要ポイント:主軸と交差軸が入れ替わってます! */
align-items: center; /* 左右中央寄せ */
justify-content: space-around; /* 上下の余白を自動調整 */
}
/* 装飾 */
.content__item {
display: flex;
align-items: center;
justify-content: center;
width: 225px;
height: 75px;
}
.content__item:nth-of-type(1) {
background-color: khaki;
}
.content__item:nth-of-type(2) {
background-color: forestgreen;
}
.content__item:nth-of-type(3) {
background-color: aquamarine;
}
.content__item:nth-of-type(4) {
background-color: tomato;
}
.content__item:nth-of-type(5) {
background-color: saddlebrown;
}

先輩くん
display:flexを指定しているのに、アイテムが縦並びになっているね!