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

如何使百分比宽度的.child-long不挤压像素宽度的.child-short,仅自身收缩?

解决Flex布局中百分比宽度子元素不挤压固定宽度子元素的问题

要实现.child-long不挤压固定宽度的.child-short,仅自身自适应收缩,只需调整两个子元素的Flex属性:

  1. 给.child-short添加flex-shrink: 0,禁止它在空间不足时被收缩,确保固定宽度始终生效;
  2. 修改.child-long的宽度设置,让它自动占据父容器剩余空间,同时允许在空间不足时收缩。

修改后的完整代码:

.parent{
  width: 100%;
  height: 200px;
  border: solid green 2px;
  margin: 10px;
  padding: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.child-long{
  height: 100%;
  flex: 1; /* 等价于 flex-grow:1, flex-shrink:1, flex-basis:0%,自动填充剩余空间并允许收缩 */
  background-color: red;
}
.child-short{
  height: 100%;
  width: 400px;
  flex-shrink: 0; /* 禁止收缩,保持固定宽度 */
  background-color: green;
}
<div class="parent">
  <div class="child-long"></div>
  <div class="child-short"></div>
</div>

关键属性解释:

  • flex-shrink: 0:默认值为1,设置为0后,元素不会在容器空间不足时被压缩,能严格保持自身设定的固定宽度。
  • flex: 1:让.child-long自动占据父容器除.child-short以外的所有剩余空间;当容器宽度小于两者总宽度时,.child-long会自动收缩,而.child-short宽度不受影响。

内容的提问来源于stack exchange,提问作者Rumata

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:50:37