FlexBoxとは?
今更ではありますが、親要素にdisplay: flex
を指定することで、子要素をいい感じに並べてくれる便利なものです。
例えば
<div class="parent">
<p class="child">子要素1</p>
<p class="child">子要素2</p>
</div>
このhtmlに対して
.parent {
width: 500px;
padding: 10px;
background-color: #e8f7ff;
}
.child {
width: 100px;
padding: 5px;
background-color: #f8a0a1;
}
CSSに1行足してFlexBoxにすると、
.parent {
width: 500px;
padding: 10px;
background-color: #e8f7ff;
display: flex; /* 追加 */
}
.child {
width: 100px;
padding: 5px;
background-color: #f8a0a1;
}
こう並びます。
justify-content
などを使うことで、左右両端揃えや中央揃えなども思いのままという便利なプロパティです。
このdisplay: flex
と組み合わせて使うプロパティの中で、flex-direction
というものが存在するのですが、ご存知でしょうか?
今回はこのflex-direction
についてちょっとだけ書いてみようと思います。
flex-directionとは?
先ほどのdisplay: flex
ですが、FlexBoxにした親要素に対して指定するプロパティで、子要素の並べ方を指定するものです。
実はこれを使うと、子要素を縦に並べたり逆から並べたりできます。
具体的には
.parent {
width: 500px;
padding: 10px;
background-color: #e8f7ff;
display: flex;
flex-direction: column; /* 追加 */
}
.child {
width: 100px;
padding: 5px;
background-color: #f8a0a1;
}
こうすることで、子要素は
こんな感じで縦に並びます。
では、例えば親要素の高さを変えて、justify-content: space-between
を指定するとどうなるでしょう。
.parent {
width: 500px;
height: 300px; /* 追加 */
padding: 10px;
background-color: #e8f7ff;
display: flex;
justify-content: space-between; /* 追加 */
flex-direction: column;
}
.child {
width: 100px;
padding: 5px;
background-color: #f8a0a1;
}
縦幅に合わせて上下両端揃えになります。
通常のFlexBoxだと左右両端揃えになるので、これはちょっと意外でした。
また、flex-direction: column-reverse
を使うとどうなるでしょうか。
.parent {
width: 500px;
height: 300px;
padding: 10px;
background-color: #e8f7ff;
display: flex;
justify-content: space-between;
flex-direction: column-reverse;
}
.child {
width: 100px;
padding: 5px;
background-color: #f8a0a1;
}
こんな感じで子要素がひっくり返ります。
ここで、justify-content: flex-start
を使うと…
.parent {
width: 500px;
height: 300px;
padding: 10px;
background-color: #e8f7ff;
display: flex;
justify-content: flex-start;
flex-direction: column-reverse;
}
.child {
width: 100px;
padding: 5px;
background-color: #f8a0a1;
}
start
なのに下に寄りました。
reverseとあるように、箱自体がひっくり返ったようになり、子要素は逆から並ぶようになります。
同様に、flex-direction: row-reverse
を使うと
.parent {
width: 500px;
height: 300px;
padding: 10px;
background-color: #e8f7ff;
display: flex;
justify-content: flex-start;
flex-direction: row-reverse;
}
.child {
width: 100px;
padding: 5px;
background-color: #f8a0a1;
}
こんな感じで、flex-direction
とjustify-content
を組み合わせると結構面白いことができます。
まとめ
- 横に並べるときは
flex-direction: row
(デフォルト) - 縦に並べるときは
flex-direction: column
-
flex-direction: row-reverse
でひっくり返すと、justify-content
の揃え方も逆になる
実際に目で見て触ってみないと分からないことは多いですよね。
flex-direction
でreverse
をつけるとjustify-content
の揃え方も逆になるのは、当然と言えば当然ですがちょっと驚きでした。
flex-direction: column-reverse
などはあまり使う機会がないかもしれませんが、もし使う時が来た際に参考にしていただけると嬉しいです。