萬盛學電腦網

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

HTML 表格固定大小技巧:table-layout:fixed 與 CSS 尺寸控制

HTML 表格固定尺寸:CSS table-layout:fixed 完全掌握

預設下,HTML 表格會根據內容自動調整欄寬 (auto layout),導致版面不穩定。使用 CSS table-layout: fixed 可強制表格依據預設寬度渲染,大幅提升渲染效能與版面可預測性。

核心 CSS 代碼

<style>
  .fixed-table {
    width: 300px;                 /* 表格固定總寬 */
    border: 0;                    /* 移除預設邊框 */
    border-collapse: collapse;    /* 合併邊框 */
    table-layout: fixed;          /* 關鍵:固定佈局模式 */
  }
  .fixed-table td {
    border: 1px solid #ccc;       /* 儲存格邊框 */
    padding: 8px;
    overflow: hidden;             * 隱藏超出內容 */
    text-overflow: ellipsis;      * 超出顯示省略號 */
    white-space: nowrap;          * 強制不換行 */
  }
</style>

<table class="fixed-table">
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>

table-layout 對比

特性auto (預設)fixed
演算法分析所有儲存格內容再計算寬度僅依第一列 (或 <col>) 寬度計算
渲染速度較慢 (大表格明顯)極快,適合大量資料
寬度穩定性內容撐開,版面易破裂嚴格遵守設定寬度
內容溢出處理自動換行或撐大需搭配 overflow 處理
適用場景簡單、內容不可預測的小表格大型資料表、固定版面、效能敏感

進階:使用 <colgroup> 精確控制欄寬

<table class="fixed-table">
  <colgroup>
    <col style="width: 50px;">   <!-- 固定 50px -->
    <col style="width: 1fr;">    <!-- 剩餘空間彈性分配 (需 Grid 支援) -->
    <col style="width: 20%;">    <!-- 百分比 -->
    <col style="width: 100px;">  <!-- 固定 100px -->
  </colgroup>
  <thead>
    <tr><th>ID</th><th>名稱</th><th>比例</th><th>操作</th></tr>
  </thead>
  <tbody>...</tbody>
</table>

搭配 <col> 可在不修改 <td> 的情況下集中管理欄寬,維護性極佳。

完整實用範例:固定表頭、固定欄寬、長文字省略

<div class="table-wrapper" style="height: 300px; overflow-y: auto;">
  <table class="fixed-table">
    <colgroup>
      <col style="width: 60px;">
      <col style="width: 200px;">
      <col style="width: 1fr;">
    </colgroup>
    <thead>
      <tr><th>編號</th><th>商品名稱</th><th>詳細說明</th></tr>
    </thead>
    <tbody>
      <tr><td>001</td><td>超長商品名稱會自動截斷顯示省略號</td><td>這裡是很長的說明文字...</td></tr>
      <!-- 更多列 -->
    </tbody>
  </table>
</div>

掌握 table-layout: fixed 讓表格版面不再崩壞,是處理大量表格資料的關鍵技能。

copyright © 萬盛學電腦網 all rights reserved