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

Flex两列布局:窗口缩放时如何保持左侧列宽度固定

解决Flex布局左侧固定宽度不收缩的问题

你的代码里左侧列设置了固定宽度,但Flex布局默认每个项目的flex-shrink属性值为1——当容器宽度不足时,项目会自动收缩来适应空间,这就是窗口缩放时左侧列宽度变化的原因。

要让左侧列始终保持固定宽度,只需给.left类添加flex-shrink: 0,禁止它被压缩:

.container{
    display: flex;
    height: 50px;
}

.left {
  border: 1px solid red;
  width: 400px;
  flex-shrink: 0; /* 关键:禁止收缩 */
}

.right {
  border: 1px solid blue;
  flex-grow: 1
}

你也可以用flex属性简写,把宽度和禁止收缩合并成一行,效果完全一致:

.left {
  border: 1px solid red;
  flex: 0 0 400px; /* 依次对应 flex-grow flex-shrink flex-basis */
}

修改后的完整代码示例:

CSS

.container{
    display: flex;
    height: 50px;
    margin-bottom: 10px; /* 增加间距区分两个容器 */
}

.left {
  border: 1px solid red;
  flex: 0 0 400px;
}

.right {
  border: 1px solid blue;
  flex-grow: 1;
  /* 可选:防止右侧长文本溢出撑破布局 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

HTML

<div class="container">
    <div class="left">
        left aligned column
    </div>    
    <div class="right">
        I want the right column to take up the rest of the space while keeping the left item's width when the window is resized
    </div>
</div>
<div class="container">
    <div class="left">
        left aligned column
    </div>    
    <div class="right">
        short text
    </div>
</div>

这样无论窗口怎么缩放,左侧列都会保持400px宽度,右侧列自动填充剩余空间;即使右侧文本很长,也不会挤压左侧列(加上溢出处理还能避免文本超出容器)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 06:54:35