表格固定寬度、長文字不換行截斷、超出隱藏是常見需求。關鍵在於 table-layout: fixed 配合 overflow、text-overflow、white-space 三大 CSS 屬性。
.table-fixed {
width: 100%;
table-layout: fixed; /* 關鍵:啟用固定佈局 */
border-collapse: collapse;
}
.table-fixed th,
.table-fixed td {
padding: 10px 12px;
border: 1px solid #e0e0e0;
/* 文字截斷三件套 */
white-space: nowrap; /* 強制不換行 */
overflow: hidden; /* 超出隱藏 */
text-overflow: ellipsis; /* 顯示省略號 */
}
/* 指定欄寬度 */
.col-id { width: 60px; }
.col-name { width: 150px; }
.col-desc { width: auto; } /* 彈性佔滿剩餘 */
.col-action { width: 100px; }
<table class="table-fixed">
<colgroup>
<col class="col-id">
<col class="col-name">
<col class="col-desc">
<col class="col-action">
</colgroup>
<thead>
<tr>
<th>ID</th>
<th>名稱</th>
<th>描述</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>產品名稱很長可能超出欄寬</td>
<td>這是一段很長的描述文字會被截斷顯示省略號</td>
<td><button>編輯</button></td>
</tr>
</tbody>
</table>
若需長文字自動換行而非截斷:
.table-wrap td {
white-space: normal; /* 允許換行 */
word-wrap: break-word; /* 舊屬性,相容性用 */
overflow-wrap: break-word; /* 現代標準屬性 */
word-break: break-word; /* 中文斷詞建議 */
}
/* 針對英文/連續字符 */
.break-all {
word-break: break-all; /* 任意字符斷行 */
}
<style>
.ellipsis-cell {
position: relative;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px; /* 或用 col 定寬 */
}
.ellipsis-cell:hover::after {
content: attr(data-full);
position: absolute;
left: 0; top: 100%;
background: #333;
color: #fff;
padding: 6px 10px;
border-radius: 4px;
white-space: normal;
width: max-content;
max-width: 300px;
z-index: 100;
font-size: 13px;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}
</style>
<td class="ellipsis-cell" data-full="完整的長文字內容...">
完整的長文字內容會被截斷...
</td>
@media (max-width: 768px) {
.table-fixed {
display: block;
overflow-x: auto;
white-space: nowrap;
}
.table-fixed thead,
.table-fixed tbody {
display: table;
width: max-content;
}
}
/* 列印時展開 */
@media print {
.table-fixed td {
white-space: normal;
overflow: visible;
text-overflow: clip;
}
}
| 症狀 | 原因 | 修正 |
|---|---|---|
| 寬度設定無效 | 缺 table-layout: fixed |
加在 table 上 |
| 省略號不顯示 | 缺 white-space: nowrap |
三件套缺一不可 |
| 中文不換行/不截斷 | 無 word-break |
加 word-break: break-all |
| 固定欄被撐開 | td 無 overflow:hidden | 檢查三件套完整性 |
| 行高異常 | line-height 衝突 | 統一設定 line-height |
function autoFitColumns(table) {
table.style.tableLayout = 'auto';
// 瀏覽器計算最佳寬度
const widths = Array.from(table.rows[0].cells).map(td => td.offsetWidth);
table.style.tableLayout = 'fixed';
Array.from(table.rows[0].cells).forEach((td, i) => {
td.style.width = widths[i] + 'px';
});
}
掌握 table-layout: fixed 核心機制,配合截斷三件套,表格佈局穩如磐石。