flexboxを使ってみましょう
flex-container
初期状態
<div class="flex-item">item</div>
<div class="flex-item">item</div>
<div class="flex-item">item</div>
<div class="flex-item">item</div>
<div class="flex-item">item</div>
</div>
このitemたちを横並びにしたい
.flex-container{
display: flex;
}
flex-containerにできるいろいろ
justify-content横方向の位置
全体の幅に合わせてitemをどのように配置するかを指定します。
containerのjustify-contentにspace-betweenを指定すると、左右は余白なしで残り余白を均等割りします。
.flex-container{
display: flex;
justify-content: space-between;
}
justify-content:
flex-start左寄せ(デフォルト)
flex-end右寄せ
center中央寄せ
space-between残り余白の均等割り
space-around左右余白 + 均等割り
flex-wrapitemの折り返しの指定
全体の幅からはみ出す時のitemの折り返しを指定します。
containerにflex-wrap: wrap;を指定すると、はみ出す場合折り返します。
.flex-container{
display: flex;
flex-wrap: wrap;
}
flex-wrap:
nowrap折り返し無し(デフォルト)
wrapはみ出す場合折り返す
wrap-reverse幅が狭くなると上へと折り返す
align-items縦方向の位置
縦方向にitemをどのように配置するかを指定します。
containerのalign-itemsにcenterを指定すると、itemの中央揃えで配置されます。
.flex-container{
display: flex;
align-items: center;
}
.flex-container{
display: flex;
align-items: baseline;
}
align-items:
stretch(デフォルト)
flex-start上寄せ
flex-end下寄せ
center中央寄せ
baseline文字のベースラインに合わせる
flex-directionitemを縦並び・横並びにする
.flex-container{
flex-direction: column-reverse;
}
.flex-item{
width: 200px;
}
flex-direction:
row横並び(デフォルト)
row-reverse横並びで順番反対
column縦並び
column-reverse縦並びで順番反対
align-content複数行にまたがった縦並びの位置
.flex-container{
display: flex;
align-content:space-between;
flex-wrap: wrap;
}
align-content:
stretch(デフォルト)
flex-start上寄せ
flex-end下寄せ
center中央寄せ
space-between
space-around
flex-itemにできるいろいろ
orderitemの並ぶ順序
.item1{
order: 1;
}
order:
0(デフォルト)
2数値で指定
flex-grow余りがあった時のitemの伸びる倍率
.item1{
flex-grow: 1;
}
.item2{
flex-grow: 2;
}
flex-grow:
0(デフォルト)
2数値で指定
flex-shrinkitemの縮む倍率
flex-shrink:
1(デフォルト)
2数値で指定
flex-basisベースとなる長さ、或いは最小の長さ
.item1{
flex-basis: 350px;
}
flex-basis:
auto(デフォルト)
350px数値で指定
flexflex-grow,flex-shrink,flex-basisをまとめて指定
.flex-item{
flex: 1 1 30%;
}
使用例
沢山のBOXを1列の個数を保ってflexで並べる
See the Pen flex by noce (@miuratta) on CodePen.
沢山のBOXを最低の幅を保ってflexで並べる
See the Pen flex by noce (@miuratta) on CodePen.
flexboxを使ってロゴを左、メニューを右に配置する
See the Pen flexbox by noce (@miuratta) on CodePen.
まず、単純に横並びにします。
flex-containerにdisplay: flex;を1行加えるだけで、floatを使うより簡単に横並びになります。