問題
3つのボックスにflex-grow
を1:2:1の比率で設定したのに、期待した比率で表示されません。なぜでしょうか?
HTML
<div class="container">
<div class="item item1">アイテム1</div>
<div class="item item2">アイテム2はとても長いテキストが入っています</div>
<div class="item item3">アイテム3</div>
</div>
CSS
.container {
display: flex;
background-color: #f5f5f5;
padding: 10px;
gap: 10px;
}
.item {
padding: 15px;
color: white;
}
.item1 {
background-color: #FF5722;
flex-grow: 1;
}
.item2 {
background-color: #4CAF50;
flex-grow: 2;
}
.item3 {
background-color: #2196F3;
flex-grow: 1;
}
実行結果
アイテム1
アイテム2はとても長いテキストが入っています
アイテム3
※ 1:2:1の比率になっていないように見えます
🔧 実際に試してみよう(リアルタイム更新)
上部でHTMLまたはCSSタブを選択して編集すると、下部の結果エリアがリアルタイムで更新されます。
CSSの flex-basis: 0;
を追加して、違いを確認してみましょう。
📺 ライブプレビュー
更新中
ヒント
クリックしてヒントを表示
flex-grow
は余剰スペースを分配する比率を指定します。
要素のコンテンツサイズが異なる場合、最終的なサイズは「基本サイズ + 分配された余剰スペース」になります。
完全な比率で表示するには、基本サイズを制御する必要があります。
解答
クリックして解答を表示
問題の原因
flex-grow
は要素の全体サイズの比率ではなく、余剰スペースの分配比率を指定します。
flex-growの仕組み
- 基本サイズの計算:各アイテムのコンテンツサイズ(flex-basisまたはwidth、内容による自然な幅)
- 余剰スペースの計算:コンテナ幅 - 全アイテムの基本サイズの合計
- 余剰スペースの分配:flex-growの比率に従って分配
- 最終サイズ:基本サイズ + 分配された余剰スペース
例:アイテム2のコンテンツが長い場合、基本サイズが大きくなるため、最終的な幅の比率が1:2:1にならない
修正方法
方法1: flex-basisを0に設定
.item {
padding: 15px;
color: white;
flex-basis: 0; /* 基本サイズを0にする */
}
.item1 {
background-color: #FF5722;
flex-grow: 1;
}
.item2 {
background-color: #4CAF50;
flex-grow: 2;
}
.item3 {
background-color: #2196F3;
flex-grow: 1;
}
修正後の結果
アイテム1
アイテム2はとても長いテキストが入っています
アイテム3
※ きれいに1:2:1の比率で表示されます
方法2: flexショートハンドを使用
.item1 {
background-color: #FF5722;
flex: 1; /* flex-grow: 1, flex-shrink: 1, flex-basis: 0 */
}
.item2 {
background-color: #4CAF50;
flex: 2; /* flex-grow: 2, flex-shrink: 1, flex-basis: 0 */
}
.item3 {
background-color: #2196F3;
flex: 1; /* flex-grow: 1, flex-shrink: 1, flex-basis: 0 */
}
方法3: min-widthを設定(コンテンツを無視)
.item {
padding: 15px;
color: white;
flex-basis: 0;
min-width: 0; /* コンテンツの最小幅を無視 */
overflow: hidden; /* はみ出し部分を隠す */
text-overflow: ellipsis; /* 省略記号を表示 */
white-space: nowrap; /* 改行を防ぐ */
}
flexプロパティの値の意味
記述 | flex-grow | flex-shrink | flex-basis |
---|---|---|---|
flex: 1 |
1 | 1 | 0 |
flex: auto |
1 | 1 | auto |
flex: none |
0 | 0 | auto |
flex: 1 1 100px |
1 | 1 | 100px |
覚えておくポイント
flex-grow
は余剰スペースの分配比率(要素全体の比率ではない)- 正確な比率にするには
flex-basis: 0
を設定 flex: 1
のショートハンドは自動的にflex-basis: 0
を設定- コンテンツのサイズを完全に無視したい場合は
min-width: 0
も必要