萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML 表格寬度控制完整方案

表格寬度控制:從屬性到 CSS 現代最佳實踐

控制表格寬度是佈局常見需求。現代開發應棄用 HTML 屬性,全面擁抱 CSS 方案。

已棄用:HTML width 屬性

<!-- 不推薦 -->
<table width="400">
  <tr>
    <td width="100">A</td>
    <td width="100">B</td>
    <td width="100">C</td>
    <td width="100">D</td>
  </tr>
</table>

缺點:混合結構與表現、無響應式、維護困難、HTML5 標準不推薦。

現代 CSS 方案

1. 表格整體寬度

table {
  width: 100%;        /* 填滿容器 */
  width: 800px;       /* 固定寬度 */
  width: 50vw;        /* 視窗百分比 */
  max-width: 1200px;  /* 最大限制 */
  min-width: 300px;   /* 最小限制 */
}

2. 欄位寬度分配

/* 固定像素 */
td:nth-child(1) { width: 100px; }
td:nth-child(2) { width: 200px; }

/* 百分比分配 (合計 100%) */
td.col-1 { width: 20%; }
td.col-2 { width: 30%; }
td.col-3 { width: 50%; }

/* 內容自適應 + 剩餘空間分配 */
td.fixed { width: 120px; }
td.auto { width: auto; }  /* 瀏覽器自動分配剩餘空間 */

3. 表格佈局算法控制

table {
  table-layout: fixed;  /* 關鍵:固定佈局算法 */
  width: 100%;
}

table {
  table-layout: auto;   /* 預設:自動算法,根據內容計算 */
}

table-layout: fixed 優勢:

  • 渲染更快 (單次遍歷決定寬度)
  • 欄寬嚴格遵守 CSS 設定,不受內容撐大
  • 配合 overflow: hidden、text-overflow: ellipsis 實現文字截斷

響應式表格策略

方案 A:水平滾動容器 (最簡單)

.table-wrapper {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}
table {
  min-width: 600px;  /* 觸發滾動的最小寬度 */
}

方案 B:堆疊模式 (行變卡片)

@media (max-width: 600px) {
  table, thead, tbody, th, td, tr { display: block; }
  thead { display: none; }  /* 隱藏表頭,用 data-label 替代 */
  td { 
    position: relative;
    padding-left: 50%; 
    border: none; 
    border-bottom: 1px solid #eee;
  }
  td::before {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    content: attr(data-label);
    font-weight: bold;
  }
}

HTML 需添加 data-label 屬性:<td data-label="產品">...</td>

方案 C:關鍵欄固定、其餘滾動

.table-container {
  overflow-x: auto;
}
table {
  width: max-content;
}
th:first-child, td:first-child {
  position: sticky;
  left: 0;
  background: white;
  z-index: 1;
  box-shadow: 2px 0 5px rgba(0,0,0,0.1);
}

常見問題排查

現象原因解決
設寬度不生效table-layout:auto + 內容撐大設 table-layout: fixed
百分比寬度失效父容器無寬度父元素設定寬度或 width: 100%
邊框導致寬度超出box-sizing: content-box (預設)box-sizing: border-box 全域重置
合併儲存格寬度異常colspan 跨列計算複雜用 <col> 定義欄寬、避免複雜合併

最佳實踐總結

  1. 全域 box-sizing: border-box
  2. 表格 table-layout: fixed + width: 100%
  3. 關鍵欄 <col style="width: 120px"> 定義
  4. 內容截斷:overflow: hidden; text-overflow: ellipsis; white-space: nowrap
  5. 響應式:優先水平滾動,次選堆疊模式
  6. 無障礙:<th scope="col|row">、<caption>、足夠對比度

表格寬度控制核心在於 CSS table-layout: fixed 與響應式策略的結合,徹底拋棄 HTML width 屬性。

copyright © 萬盛學電腦網 all rights reserved