萬盛學電腦網

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

HTML 表格基礎樣式速查:佈局、邊框與背景的 CSS 實作指南

表格樣式重置與基礎佈局

HTML 表格(<table>)預設樣式在各瀏覽器差異極大,實務上建議先進行重置,再套用自訂樣式。以下是一個現代化、響應式友好的表格基礎樣式範例:

/* 1. 表格重置:合併邊框、移除間距、固定佈局演算法 */
.table-base {
  width: 100%;
  max-width: 800px;       /* 最大寬度限制,防止過寬 */
  margin: 0 auto 8px;     /* 水平置中、底部間距 */
  border-collapse: collapse; /* 合併邊框,避免雙線 */
  table-layout: fixed;    /* 固定佈局:依  或首行寬度計算,渲染更快、更穩定 */
  background-color: #eff7ff; /* 淺藍背景 */
  border: 1px solid #96c2f1; /* 外框邊框 */
  font-size: 14px;
  line-height: 1.5;
}

/* 2. 儲存格通用樣式 */
.table-base th,
.table-base td {
  padding: 12px 16px;
  border: 1px solid #d0e6f6; /* 內部邊框色淡於外框 */
  text-align: left;
  vertical-align: middle;
  word-break: break-word;   /* 長英文/網址自動換行 */
  overflow-wrap: anywhere;  /* 更強的換行保護 */
}

/* 3. 表頭樣式區分 */
.table-base thead th {
  background-color: #d6eaff;
  color: #1a3a5c;
  font-weight: 600;
  white-space: nowrap;      /* 表頭預設不換行 */
}

/* 4. 條紋效果:增強可讀性 */
.table-base tbody tr:nth-child(even) {
  background-color: #f5faff;
}

/* 5. 滑過高亮:互動回饋 */
.table-base tbody tr:hover {
  background-color: #e8f2ff;
  transition: background-color 0.2s ease;
}

/* 6. 響應式處理:小螢幕橫向滾動 */
@media (max-width: 640px) {
  .table-responsive {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }
  .table-responsive .table-base {
    min-width: 600px; /* 確保內容不被壓縮 */
  }
}

HTML 結構範例

<div class="table-responsive">
  <table class="table-base">
    <thead>
      <tr>
        <th scope="col">產品名稱</th>
        <th scope="col">價格</th>
        <th scope="col">庫存狀態</th>
        <th scope="col">操作</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>高效能筆記型電腦</td>
        <td>NT$ 45,900</td>
        <td><span class="badge badge-success">現貨</span></td>
        <td><button class="btn btn-primary">加入購物車</button></td>
      </tr>
      <tr>
        <td>無線降噪耳機</td>
        <td>NT$ 8,990</td>
        <td><span class="badge badge-warning">預購中</span></td>
        <td><button class="btn btn-outline">通知我</button></td>
      </tr>
    </tbody>
  </table>
</div>

關鍵屬性解析

屬性推薦值用途說明
border-collapsecollapse合併相鄰邊框為單線,避免雙線框線
table-layoutfixed固定佈局模式,依 <col> 或首列定寬,渲染效能優於 auto,寬度計算可預測
word-break / overflow-wrapbreak-word / anywhere防止長串字元(URL、ID)撐破欄寬
vertical-alignmiddle儲存格內容垂直置中,視覺更平衡
:nth-child(even)—純 CSS 實現斑馬紋,無需 JS 或交替 class

進階技巧:固定表頭

長表格滾動時固定 <thead>,純 CSS 方案(需容器限高):

.table-sticky-wrap {
  max-height: 400px;
  overflow-y: auto;
}
.table-sticky-wrap thead th {
  position: sticky;
  top: 0;
  z-index: 1;
  background: #d6eaff; /* 必須有實體背景色,否則滾動時會透出內容 */
}

無障礙提醒

  • 務必使用 <th scope="col|row"> 標示表頭範圍,螢幕閱讀器才能正確關聯數據。
  • 複雜表格添加 <caption> 說明表格用途。
  • 避免使用巢狀表格佈局,語意化結構是無障礙基石。

掌握這些基礎樣式模組,即可快速建構美觀、無障礙、響應式的資料表格,並作為專案共用元件持續迭代優化。

copyright © 萬盛學電腦網 all rights reserved