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

Flexbox右侧项无法适配内容并显示横向滚动条问题求助

问题:Flex容器右侧子元素无法实现横向滚动

我有一个Flex布局容器,包含左侧固定宽度的子元素和右侧需要横向滚动的子元素,但当前右侧的超长内容无法触发横向滚动条。代码示例如下:

原CSS代码

.container {
  display: flex;
  overflow: hidden;
  height: 300px;
}

.left-side {
  min-width: 100px;
  background-color: red;
  text-align: center;
}

.right-side {
  background-color: blue;
  overflow-x: auto;
}

.right-side > div {
  height: 50px;
  background-color: yellow;
  text-align: center;
  line-height: 50px;
}

.right-side > p {
  white-space: nowrap;
  background-color: yellow;
}

.notes {
  padding-top: 20px;
}

原HTML代码

<div class="container">
  <div class="left-side">
    left side
  </div>
  <div class="right-side">
    <div>
      right side
    </div>
    <p>
      Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph
      Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph Paragraph
      Paragraph Paragraph Paragraph Paragraph
    </p>
  </div>
</div>

解决方法

问题根源在于Flex布局中,子元素默认的min-width: auto会阻止元素收缩到内容宽度以下,导致overflow-x: auto无法触发横向滚动。只需修改.right-side的样式即可解决:

修改后的CSS代码

.container {
  display: flex;
  overflow: hidden;
  height: 300px;
}

.left-side {
  min-width: 100px;
  background-color: red;
  text-align: center;
}

.right-side {
  flex: 1; /* 占据容器剩余空间 */
  min-width: 0; /* 打破默认min-width限制,允许元素收缩 */
  background-color: blue;
  overflow-x: auto;
}

.right-side > div {
  height: 50px;
  background-color: yellow;
  text-align: center;
  line-height: 50px;
}

.right-side > p {
  white-space: nowrap;
  background-color: yellow;
}

.notes {
  padding-top: 20px;
}

关键修改说明

  • flex: 1:让右侧子元素占据Flex容器中左侧元素之外的所有剩余空间
  • min-width: 0:覆盖Flex项默认的min-width: auto,允许元素的宽度被压缩到小于内部内容的宽度,从而触发overflow-x: auto的横向滚动效果

修改后,左侧元素保持固定宽度,右侧元素会填满剩余空间,当内部的超长文本超出容器宽度时,会自动显示横向滚动条。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:28:34