表格儲存格 <td> 內的文字排版,常見需求包含首行縮進、內距控制、自動編號。CSS 提供完整解決方案。
td {
text-indent: 2em; /* 2 個字元寬度 (相對於字體大小) */
/* 或固定單位 */
text-indent: 24px;
}
display: table-cell 生效,<td> 預設即為 table-cell。<p>),建議對 td p 設定。td, th {
padding: 12px 16px; /* 上下 12px、左右 16px */
box-sizing: border-box; /* 含 padding 在 width 內 */
}
取代舊屬性 cellpadding,支援四邊獨立控制、響應式調整。
tbody {
counter-reset: row-num;
}
tbody tr::before {
counter-increment: row-num;
content: counter(row-num) ". ";
display: table-cell; /* 偽元素參與表格佈局 */
width: 40px;
text-align: right;
padding-right: 12px;
font-weight: 600;
color: #666;
}
無需在 HTML 寫死序號,刪減/排序列自動同步。
<style>
.article-table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
.article-table th,
.article-table td {
border: 1px solid #ddd;
padding: 10px 12px;
vertical-align: top;
}
.article-table tbody {
counter-reset: row;
}
.article-table tbody tr::before {
counter-increment: row;
content: counter(row);
display: table-cell;
width: 40px;
text-align: center;
background: #f5f5f5;
border-right: 1px solid #ddd;
}
.article-table td.content {
text-indent: 2em;
line-height: 1.7;
}
.article-table tbody tr:nth-child(even) td { background: #fafafa; }
</style>
<table class="article-table">
<thead><tr><th>#</th><th>內容段落</th></tr></thead>
<tbody>
<tr><td class="content">第一段內容...</td></tr>
<tr><td class="content">第二段內容...</td></tr>
</tbody>
</table>
善用 CSS 排版屬性,讓表格內文字閱讀體驗媲美文章頁面。