概述

在开发中,我们常遇到这种布局:A、B、C 三段文本长度不固定,其中 A、C 占用空间较少,需要完整显示;而 B 是自适应区域,超出部分需省略显示。A 与 B 共享同一容器,右侧的 "Live" 按钮与该容器同级,容器应占据除 "Live" 之外的所有剩余空间。
HTML 结构如下:
html
<div class="wrap">
<div class="infos">
<div>Soccer</div>
<div class="self">Campeonato De Reserva De Primera Division C</div>
</div>
<div class="live">Live</div>
</div>
如果按照常规思路编写 CSS,比如:
css
.wrap {
display: flex;
align-items: center;
width: 350px;
border: 1px dashed #ccc;
padding: 4px 16px;
gap: 16px;
}
.infos {
flex: 1;
display: flex;
gap: 8px;
align-items: center;
}
.self {
flex: 1;
padding: 4px;
background-color: silver;
border-radius: 6px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.live {
padding: 4px 16px;
background: cornflowerblue;
border-radius: 6px;
color: white;
flex-shrink: 0;
}
渲染效果往往会出现问题,示例如下:

可以看到,.self 会被内容撑开,导致 "Live" 被挤出容器。
异常分析
出现这种情况的根本原因是:
在 Flex 布局中,每个子元素的默认 min-width 是 auto。这意味着子元素的内容(文本)不会被压缩,即使父容器空间不足。
只有显式将 min-width 设为 0,才能让子项在空间受限时被压缩,从而使 overflow: hidden 与 text-overflow: ellipsis 生效。
更关键的是:
如果布局中存在嵌套的 flex 容器,那么 所有中间层的容器 也需要显式设置 min-width: 0,否则内部文本依然不会被压缩。
本例结构如下:
scss
.wrap (display: flex)
├── .infos (display: flex)
│ ├── div (Soccer)
│ └── .self (文字太长)
└── .live
.infos 是 .wrap 的 flex 子项,默认 min-width: auto,会阻止内部 .self 被压缩。
因此,.infos 和 .self 都必须加上 min-width: 0。
实现
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flex 布局下文字省略不生效?原因其实很简单</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.wrap {
display: flex;
align-items: center;
width: 350px;
border: 1px dashed #ccc;
padding: 4px 16px;
gap: 16px;
}
.infos {
flex: 1;
display: flex;
gap: 8px;
align-items: center;
min-width: 0; /* ✅ 必加,让内部 .self 可以被压缩 */
}
.self {
flex: 1;
min-width: 0; /* ✅ 必加,否则 ellipsis 不生效 */
padding: 4px;
background-color: silver;
border-radius: 6px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.live {
padding: 4px 16px;
background: cornflowerblue;
border-radius: 6px;
color: white;
flex-shrink: 0;
}
</style>
</head>
<body>
<div class="wrap">
<div class="infos">
<div>Soccer</div>
<div class="self">Campeonato De Reserva De Primera Division C</div>
</div>
<div class="live">Live</div>
</div>
</body>
</html>
总结
层级 | 是否需要 min-width: 0 | 原因 |
---|---|---|
.wrap | ❌ | 最外层容器,不需要压缩 |
.infos | ✅ | 它是 .wrap 的 flex 子项,需要允许内部压缩 |
.self | ✅ | 它是 .infos 的 flex 子项,真正要被省略的元素 |
结论:在嵌套的 Flex 布局中,任何包裹文字的中间层都必须显式设置 min-width: 0,否则 text-overflow: ellipsis 永远不会生效。