表格裡的文字太長會撐破欄寬,這時候不必動用 JavaScript 去截字串,靠 CSS 就能讓溢出的部分自動摺成「…」。
關鍵是 table-layout:fixed 加上 overflow:hidden 與 text-overflow:ellipsis 這三個屬性搭配,再補一個 nowrap 防止換行:
<table width="550" border="0" cellpadding="5" cellspacing="1" bgcolor="#007373" style="table-layout:fixed"> <tr> <th nowrap bgcolor="#159AA2" style="overflow:hidden; text-overflow:ellipsis; color:#FFFFFF;">List1</th> <th nowrap bgcolor="#159AA2" style="overflow:hidden; text-overflow:ellipsis; color:#FFFFFF;">List2</th> <th nowrap bgcolor="#159AA2" style="overflow:hidden; text-overflow:ellipsis; color:#FFFFFF;">List3</th> </tr> <tr> <td nowrap bgcolor="#E8FFFF" style="overflow:hidden; text-overflow:ellipsis;">用CSS實現超長字段被省略的簡單方法</td> <td nowrap bgcolor="#E8FFFF" style="overflow:hidden; text-overflow:ellipsis;">用CSS實現超長字段被省略的簡單方法</td> <td nowrap bgcolor="#E8FFFF" style="overflow:hidden; text-overflow:ellipsis;">用CSS實現超長字段被省略的簡單方法</td> </tr> </table>
table-layout:fixed 讓表格依據第一列或指定寬度平均分配欄寬,不再被內容長度牽著走。少了這一行,長文字會硬把欄位撐開,後面的省略號自然無從發生。
overflow:hidden 把超出容器範圍的內容裁掉,這是省略號能出現的前提。
text-overflow:ellipsis 才是真正的重點,它決定裁切處要顯示省略標記而非硬生生切斷。
nowrap 則是防止文字主動換行;一旦換行了,就不算「溢出」,省略號也就不會啟動。
這幾個屬性都是作用在區塊層級的元素上,所以 th 與 td 都能直接套用。實務上比較乾淨的做法是寫成一個 class 共用,例如 .ellipsis{overflow:hidden; text-overflow:ellipsis; white-space:nowrap;},套用起來比每格重寫 inline style 清爽得多。