css3のflex boxが便利すぎて1日に1回は使うので、とりあえず普段よく使うものをまとめてみました
使い方の基本
- 横並びにしたいブロック要素の一つ上の階層に
display: flex
を指定するだけ
index.html
<div class="wrapper">
<div class="element">BLOCK1</div>
<div class="element">BLOCK2</div>
<div class="element">BLOCK3</div>
</div>
index.css
.wrapper{
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
}
そんな書くのかよと思われるかもしれないが、chromeなら
index.css
.wrapper{
display: flex;
}
で十分だし、何なら
common.css
.flex{
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
}
というクラスを定義しておけば
index.html
<div class="flex">
<div>BLOCK1</div>
<div>BLOCK2</div>
<div>BLOCK3</div>
</div>
これだけで簡単にブロック要素の横並びが可能。
プロパティ
flex-direction : 子要素の配置方向
index.css
.wrapper{
display: flex;
flex-direction: row; /*横並び・左から右(デフォルト)*/
flex-direction: column; /*縦並び・上から下*/
flex-direction: row-reverse; /*横並び・右から左*/
flex-direction: column-reverse; /*縦並び・下から上*/
}
flex-wrap : 子要素の折り返し設定
index.css
.wrapper{
display: flex;
flex-wrap: no-wrap; /*折り返しなし・単一行(デフォルト)*/
flex-wrap: wrap; /*折り返し有り・複数行*/
flex-wrap: wrap-reverse; /*折り返し有り・複数行・折り返し地点が逆*/
}
flex-flow : 子要素の配置・折り返し設定をまとめて記述
index.css
.wrapper{
display: flex;
flex-flow: row no-wrap; /*flex-direction + flex-wrapの記述が可能*/
flex-flow: column wrap;
}
justify-content : 水平方向の揃え方
index.css
.wrapper{
display: flex;
justify-content: flex-start; /*左(上)揃え*/
justify-content: flex-end; /*右(下)揃え*/
justify-content: center; /*中央揃え*/
justify-content: space-between; /*均等に間隔をあける*/
justify-content: space-around; /*均等に間隔をあける・両端にも間隔をあける*/
}
align-items : 垂直方向の揃え方
index.css
.wrapper{
display: flex;
align-items: flex-start; /*上(左)揃え*/
align-items: flex-end; /*下(右)揃え*/
align-items: center; /*中央揃え*/
align-items: baseline; /*ベースラインを揃える*/
align-items: stretch; /*全ての要素の高さを揃える*/
}
align-content : 複数行になった時の行の揃え方
index.css
.wrapper{
display: flex;
align-content: flex-start; /*上(左)揃え*/
align-content: flex-end; /*下(右)揃え*/
align-content: center; /*中央揃え*/
align-content: space-between; /*均等に間隔をあける*/
align-content: space-around; /*均等に間隔をあける・両端にも間隔をあける*/
}
flexボックスを使えば、面倒だった横並びがとても簡単にできるだけではなく、要素間の関係も並べ方も上下左右中央寄せもとても簡単にできます。ぜひ使ってみては!