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

如何设置Flexbox让side容器宽度固定为sideA最小宽度,sideB自动换行?

解决方案

要实现side容器宽度固定为sideA的最小不换行宽度,同时让sideB内容在该宽度内自动换行,为main留出更多空间,只需对CSS做以下关键修改:

修改后的完整代码

#top {
  display: flex;
  flex-direction: row;
  background-color: black;
  height: 100%;
}

#side {
  display: flex;
  flex-direction: column;
  background-color: red;
  height: 100%;
  /* 让side宽度由内部非换行元素(sideA)决定,不被sideB撑开 */
  width: fit-content;
}

#sideA {
  white-space: nowrap;
  background-color: green;
}

#sideB {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  background-color: orange;
  gap: 4px;
  /* 强制sideB继承side的宽度,内容超出自动换行 */
  width: 100%;
}

#main {
  background-color: yellow;
  flex-grow: 1;
  height: 100%;
}
<div id="top">
  <div id="side">
    <div id="sideA">
      Content here should expand side.
    </div>
    <div id="sideB">
      This area should not grow wider than sideA's minimum, unwrapped width.
      <button>One button</button>
      <button>Another one</button>
      <button>Here's a third</button>
      <button>And finally this one</button>
    </div>
  </div>
  <div id="main">
    This content should fill up the width not required by sideA. While side should take up exactly the width of sideA, and sideB should just wrap as needed.
    <br/><br/><br/><br/><br/><br/><br/>
    <br/><br/><br/><br/><br/><br/><br/>
  </div>
</div>

核心修改说明

  • #side新增width: fit-content:让side的宽度仅由内部最宽的非换行元素(即设置了white-space: nowrap的sideA)决定,彻底避免被sideB的内容横向撑开。
  • #sideB新增width: 100%:强制sideB继承side的宽度,内部按钮和文本会在该宽度限制下自动换行,不会扩展容器宽度。
  • #main的flex-grow调整为1:flex-grow是比例值,1足够让main占据剩余所有可用空间,无需设置过大数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:40:38