HTML 表格儲存格(<td>)預設不會自動換行長字串(如連續英文、數字、網址),導致表格撐破版面。掌握 CSS 換行屬性是解決此問題的關鍵。
| 屬性 | 關鍵值 | 適用場景 |
|---|---|---|
word-break | break-all、keep-all | 強制單字內斷行 / 保護 CJK 文字不斷行 |
overflow-wrap(word-wrap) | break-word、anywhere | 單字過長時允許斷行,較溫和 |
white-space | normal、nowrap、pre-wrap | 控制空白與換行行為 |
hyphens | auto、manual | 自動連字號斷行(需 lang 屬性) |
.table-cell-wrap {
word-break: break-word; /* 現代瀏覽器支援 */
overflow-wrap: break-word; * 兼容舊版瀏覽器 */
white-space: normal; /* 允許正常換行 */
}
<style>
.break-cell {
word-break: break-all;
max-width: 200px; /* 配合表格固定佈局 */
}
table { table-layout: fixed; width: 100%; }
</style>
<table>
<tr>
<th>訂單編號</th>
<th>追蹤網址</th>
</tr>
<tr>
<td class="break-cell">ORD-20240115-00123456789</td>
<td class="break-cell"><a href="#">https://example.com/track/very-long-tracking-number-1234567890</a></td>
</tr>
</table>
.log-cell {
white-space: pre-wrap; /* 保留換行與空白 */
font-family: monospace;
font-size: 0.85rem;
}
table-layout: fixed 配合寬度限制,否則長內容仍會撐開<td> 直接寫 <br>,改用 CSS 控制word-break: keep-all 避免字詞被拆分善用 CSS 換行屬性,讓表格在任何螢幕尺寸下都能優雅呈現長內容,是前端開發的基本功之一。