DIV CSS 佈局教程網

讓 td 內容不換行也不撐開表格的 CSS 三件套
編輯:關於JavaScript     

表格裡塞了長文字,常常會出現兩種惱人情況:文字換行把列高撐開,或者文字不換行卻把欄寬撐破。要同時解決,需要三個屬性搭配使用。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<body>
<style type="text/css">
table {width:200px; table-layout:fixed;}
td {white-space:nowrap; overflow:hidden; word-break:keep-all;}
</style>
<table border="1">
<tr>
<td style="width:50px;">測試測試測試測試測試測試測試測試測試測試</td>
<td>測試測試測試測試測試測試測試測試測試測試測試測試</td>
</tr>
<tr>
<td>測試測試測試測試測試測試測試測試測試測試測試</td>
<td>測試測試測試測試測試測試測試測試測試測試測試</td>
</tr>
</table>
</body>
</html>

三個屬性各司何職

table-layout: fixed 是前提。預設的 auto 佈局會依內容自動調整欄寬,你設定的 width 只是「建議值」。改成 fixed 後,欄寬完全由第一列(或 <col> 標籤)決定,內容再長也擠不破。

white-space: nowrap 禁止換行,讓文字維持單行。

overflow: hidden 把超出欄寬的部分裁掉,這才是真正「不撐開」的關鍵。

word-break: keep-all 是輔助,確保中文不會在字元之間被切斷換行。

實務上的補充

直接裁掉內容有時並不理想,使用者看不到完整資訊。實務上通常會再加上省略號提示:

td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

三個屬性合在一起,超出部分就會顯示為 …,讓使用者知道還有內容。

另外提醒兩點:一是 table-layout: fixed 生效後,欄寬只看第一列,所以若表格有 thead,請確認寬度是設在 thead 的 th 上;二是若需要多行截斷(例如固定顯示兩行),text-overflow 無效,應改用 -webkit-line-clamp 搭配 display: -webkit-box。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved