在開發中,我們常遇到這種佈局:A、B、C 三段文本長度不固定,其中 A、C 占用空間較少,需要完整顯示,B 是自適應區域,超出部分需省略顯示。A 與 B 屬同一容器,該容器與 C 同級,容器應佔據除 C 之外的所有剩餘空間,HTML 結構如下:
<div class="wrap">
<div class="infos">
<div>足球</div>
<div class="self">甲級聯賽預備組</div>
</div>
<div class="live">直播</div>
</div>
如果按照常規思路編寫 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 被內容撐開,導致右側 “直播” 按鈕被擠出容器。
為什麼會出現這樣的情況呢?問題的根源在於 Flex 子項的預設行為:
在 Flex 佈局中,子元素的預設 min-width 是 auto,意味著它會根據內容寬度確定最小值,導致內容不會被壓縮。
因此,當 .wrap 的空間不足時,.infos 會拒絕被壓縮,從而讓內部的 .self 也失去“省略”的機會。
要讓 .self 的 text-overflow: ellipsis 生效,必須確保它在空間不足時可以被壓縮。
解決方案也很簡單:給 .infos 設置 min-width: 0 即可。
這告訴瀏覽器,“.infos 可以比它內容更窄”,從而允許內部 .self 根據空間自動裁切。
<!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 {
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;
}
</style>
</head>
<body>
<div class="wrap">
<div class="infos">
<div>足球</div>
<div class="self">甲級聯賽預備組</div>
</div>
<div class="live">直播</div>
</div>
</body>
</html>
層級 | 是否需要 min-width: 0 | 原因 |
---|---|---|
.wrap | ❌ | 最外層容器,無需壓縮 |
.infos | ✅ | 是 .wrap 的 flex 子項,預設 min-width: auto 會阻止內部壓縮 |
.self | ❌ | 父層已允許壓縮,無需重複設置 |
結論:在 Flex 佈局中,當內部文字的省略不生效時,優先檢查文字外層的容器 是否設置了 min-width: 0。大多數情況下,只需在容器層加上這一行,就能徹底解決問題。