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

如何防止Flexbox水平扩张?实现固定列的文本溢出省略

解决Flex布局中文本溢出省略号问题

问题根源在于.row-middle作为flex子项,默认min-width: auto,当内部文本过长时会撑宽自身,既挤压右侧元素,又导致内部文本省略规则无法生效。只需给.row-middle添加一行样式即可解决:

.row-middle{
  flex:1 0 0;  
  background-color: green;
  overflow: hidden; /* 新增关键样式 */
}

修改后的完整代码

CSS

.container{
  width: 500px;
  height: 300px;
  border: 2px solid #000;
}
.row{
  width: 100%;
  height: 48px;
  background-color: dodgerblue;
  display: flex;  
  align-items:center;
}
.row-left{
  width: 60px;
  display: flex;  
  height: 100%;
  background-color: red;
  align-items: center;
  justify-content: center;
}
.row-middle{
  flex:1 0 0;  
  background-color: green;
  overflow: hidden; /* 强制容器遵守flex分配的宽度 */
}
.row-right{
  width: 100px;
  height: 100%;
  background-color: yellow;
  display: flex;
  align-items: center;
  justify-content: center;
}
.subject{
  width: 100%;
  height: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  display: flex;
  align-items: center;
  padding: 0 8px;
}

HTML

<div class="container">
  <div class="row">
    <div class="row-left">X</div>
    <div class="row-middle">
      <div class="subject">
      This is what I am supposed to look like.
      </div>
    </div>
    <div class="row-right">X</div>
  </div>
  <div class="row">
    <div class="row-left">X</div>
    <div class="row-middle">
      <div class="subject">
      This is what I look like when my text is too long.  How can we possibly fix this to hide the overflow and ellipses the text?
      </div>
    </div>
    <div class="row-right">X</div>
  </div>  
</div>

核心原理

  • overflow: hidden 强制.row-middle遵守flex布局分配的宽度,禁止内部内容撑宽容器
  • .subject的三个文本省略核心样式(overflow: hidden、white-space: nowrap、text-overflow: ellipsis)需要父容器有明确宽度限制才能生效,添加overflow: hidden后恰好满足该条件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:53:24