siroemk’s blog

フィヨルドブートキャンプで学んでいます(2020/11〜)

【CSS】片方固定、片方可変のレイアウトの作り方(flexbox)

片方固定、片方可変のレイアウト

よくある2カラムのデザイン。 片方は固定して片方は画面幅に応じて可変するレイアウトの作り方。

f:id:siroemk:20201209123655p:plain

このHTMLにCSSでレイアウトをつける。

<div class="parent">
    <div class="child-a">
     <!-- 固定幅 -->
    </div>
    <div class="child-b">
     <!-- 画面サイズに応じて可変 -->
    </div>
<div>

親である.parentにdisplay: flex;を指定して子を横並びにする。 固定幅の子(.child-a)にflex-basis: 200px;を指定して固定幅の横幅を設定。 可変の子(.child-b)にはflex-grow: 1;を指定する。

.parent {
    display: flex;
}

.child-a {    
    height: 300px;
    background-color: tomato;
    flex-basis: 200px;
}

.child-b {
    height: 300px;
    background-color: orange;
    flex-grow: 1;
}

なぜ flex-grow: 1; で可変になるのか

flex-growは親要素の余った余白を分け合う比率を指定できる。 今回の場合、すでに固定幅の.child-aflex-basis: 200px;で幅を指定しているため、flex-grow: 1;が指定された.child-bは他に分け合うものがなくなり、残った余白を独占する形となる。