You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

浏览器如何计算带flex-shrink和flex-basis的两个div高度?

如何计算flex容器中带flex-shrink元素的最终高度?

你的代码示例

CSS代码

.container { 
  height: 200px; 
  background-color: grey; 
  display: flex; 
  flex-direction: column; 
}
.top { 
  flex: 0 0 10%; 
  background-color: red; 
}
.middle { 
  flex: 0 2 20%; 
  background-color: cyan; 
}
.bottom { 
  flex: 0 1 80%; 
  background-color: orange; 
}

HTML代码

<div class="container"> 
  <div class="top">top</div> 
  <div class="middle">middle</div> 
  <div class="bottom">bottom</div> 
</div>

你对top元素的计算完全正确:它的flex-grow:0(不扩展)、flex-shrink:0(不收缩),flex-basis:10%对应容器200px高度的10%,也就是20px,这部分逻辑没问题。

接下来咱们重点拆解middle和bottom的高度计算逻辑——核心是理解flex-shrink的收缩规则:当flex容器的剩余空间不足以容纳所有元素的flex-basis总和时,浏览器会根据「元素的flex-shrink值 × 它的flex-basis像素值」的比例来分配需要收缩的空间。

具体计算步骤

  1. 计算剩余可用空间:容器总高200px,减去top的20px,剩余200-20=180px。
  2. 计算两个元素的flex-basis像素值:
    • middle的flex-basis是20% → 200×20%=40px
    • bottom的flex-basis是80% → 200×80%=160px
      两者的flex-basis总和是40+160=200px,比剩余的180px多了20px,所以总共需要收缩200-180=20px。
  3. 计算收缩权重(因子):
    收缩权重 = flex-shrink值 × flex-basis像素值
    • middle的权重:2×40=80
    • bottom的权重:1×160=160
      总权重:80+160=240
  4. 分配各自需要收缩的像素:
    每个元素收缩的像素 = 总收缩量 × (自身权重/总权重)
    • middle需要收缩:20×(80/240)≈6.67px,最终高度为40-6.67≈33.33px
    • bottom需要收缩:20×(160/240)≈13.33px,最终高度为160-13.33≈146.67px
  5. 验证结果:33.33+146.67=180px,刚好填满剩余空间,符合预期。

内容的提问来源于stack exchange,提问作者by-brt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:37:26