萬盛學電腦網

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

HTML 表格寬度控制:屬性、CSS、響應式與最佳實務

表格寬度設定方式演進

時代方法範例缺點
HTML 4 / 早期屬性 width<table width="400">混雜表現與結構、難維護、無響應式
CSS 2.1table { width: ... }table { width: 100%; }需搭配 table-layout 控制演算法
現代 RWDCSS + 媒體查詢 + 容器查詢max-width: 100%; overflow-x: auto;需處理小螢幕可用性

CSS 核心屬性

table {
  width: 100%;           /* 撐滿容器 */
  max-width: 800px;      /* 最大寬度限制 */
  table-layout: fixed;   /* 關鍵:固定佈局演算法,速度快、可控 */
}
th, td {
  width: 25%;            /* 僅在 fixed 生效時精確分配 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

table-layout: fixed 讓瀏覽器依 <col> 或第一列寬度直接計算,不需分析所有儲存格內容,大幅提升大型表格渲染速度。

<col> / <colgroup> 精確控制欄寬

<table>
  <colgroup>
    <col style="width: 50px;">       <!-- 固定 50px -->
    <col style="width: 30%;">       <!-- 30% -->
    <col style="width: 1fr;">       <-- 剩餘空間 (需 fixed) -->
    <col span="2" style="width: auto;"> <-- 兩欄自動 -->
  </colgroup>
  <thead>...</thead>
  <tbody>...</tbody>
</table>

響應式表格三大策略

1. 水平捲動容器(最簡單)

.table-wrapper { overflow-x: auto; -webkit-overflow-scrolling: touch; }
table { min-width: 600px; } /* 強制最小寬,觸發捲動 */

2. 關鍵欄固定,其餘捲動

th:first-child, td:first-child {
  position: sticky; left: 0; background: #fff; z-index: 1;
}

3. 卡片式重組(行變卡)

@media (max-width: 600px) {
  table, thead, tbody, th, td, tr { display: block; }
  thead { display: none; } /* 隱藏表頭,改用 data-label */
  td { display: flex; justify-content: space-between; padding: .5rem; border-bottom: 1px solid #eee; }
  td::before { content: attr(data-label); font-weight: bold; }
}
<td data-label="Price">$99</td>

避坑指南

  • 不要在 <td> 直接設 width 卻未設 table-layout: fixed → 瀏覽器會自動調整,結果不可預期。
  • 百分比寬度總和超過 100% 時,瀏覽器會按比例壓縮。
  • border-collapse: collapse 會合併邊框,寬度計算不含邊框;separate 則含邊框。
  • 行動裝置務必加 -webkit-overflow-scrolling: touch 體驗順滑。

延伸閱讀

copyright © 萬盛學電腦網 all rights reserved