萬盛學電腦網

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

HTML 表格欄寬控制:width 屬性、CSS width、table-layout:fixed 與 colgroup 精確分配

表格欄寬精確控制:從 HTML width 屬性遷移至 CSS table-layout:fixed + colgroup

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>
  • 混合 px/% 易衝突,瀏覽器自動調整導致不可預期。
  • 內容過長仍會撐大欄位 (auto 模式)。

CSS 現代方案:table-layout: fixed + <colgroup>

<style>
  .fixed-width-table {
    table-layout: fixed;   /* 關鍵:固定版面演算法 */
    width: 100%;
  }
  .fixed-width-table col:nth-child(1) { width: 15%; }
  .fixed-width-table col:nth-child(2) { width: 35%; }
  .fixed-width-table col:nth-child(3) { width: 50%; }
  /* 儲存格溢位處理 */
  .fixed-width-table td {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding: 8px 12px;
  }
</style>

<table class="fixed-width-table">
  <colgroup>
    <col><col><col>
  </colgroup>
  <thead><tr><th>欄位 A</th><th>欄位 B</th><th>欄位 C</th></tr></thead>
  <tbody>
    <tr><td>內容不會撐大欄寬</td><td>超長文字會自動截斷加省略號</td><td>固定 50%</td></tr>
  </tbody>
</table>

table-layout 兩種模式對比

模式演算法速度欄寬受內容影響適用場景
auto (預設)讀取所有內容計算慢 (大表格明顯)是內容決定寬度、簡單表格
fixed依 col/首列 td 寬度一次定案快否資料密集、固定版面、大型表格

最佳實踐

  1. 表格加 table-layout: fixed; width: 100%;。
  2. 使用 <colgroup><col style="width:..."> 宣告欄寬 (支援 px, %, fr-like 比例)。
  3. 儲存格加 overflow: hidden; text-overflow: ellipsis; white-space: nowrap; 防撐破。
  4. 需換行欄位改用 overflow-wrap: anywhere; 並移除 white-space: nowrap。

固定版面模式是大型資料表格效能與視覺穩定的關鍵。

copyright © 萬盛學電腦網 all rights reserved