HTML/CSS

【CSS】display:flexを縦並びにする方法

本記事では、display:flexで横並びになったアイテムを縦並びにする方法について解説しています。

HTML/CSSの学習におすすめ参考書
1冊ですべて身につくHTML&CSSとWebデザイン入門講座

本書情報
著者Mana
発売日2019/3/16
ページ数280ページ
Kindle版
レビュー
(Amazon)
(2,167件)
先輩くん
先輩くん
Amazon Kindle Unlimitedに登録すると、月額980円で読み放題だからオススメだよ!
後輩ちゃん
後輩ちゃん
初回30日間は無料だから、まだ登録したことのない人はぜひ試してみてね!

綺麗なコードが書けるようになる!
リーダブルコード-より良いコードを書くためのシンプルで実践的なテクニック

本書情報
出版社オライリージャパン
著者Dustin Boswell / Trevor Foucher
発売日2012/6/23
ページ数260ページ
レビュー
(Amazon)
(620件)
先輩くん
先輩くん
より良いコードを書きたい人におすすめの本だよ!
後輩ちゃん
後輩ちゃん
10以上前の書籍ですが、内容は今でも役に立つものばかりです!

flex-directionを使う

結論から申し上げますと、display:flexで横並びになったアイテムを縦並びにするにはflex-directionプロパティにcolumnの値を指定します。

.sample{
  display: flex;
  flex-direction: column;
}

flex-direction: column; アイテムを垂直方向に上から下へと配置する

flex-direction: column;を指定すると、主軸と交差軸が反転するため横の位置を調整する場合は「align-itemsプロパティ」を指定し、縦の位置を調整する場合「justify-contentプロパティ」を指定します。

実践:縦並びにしてみよう

実際に、下記のサンプルコードを使用して縦並びになるか確認しましょう。

<!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を指定しているのに、アイテムが縦並びになっているね!

ブログランキング・にほんブログ村へ PVアクセスランキング にほんブログ村