萬盛學電腦網

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

HTML 表格邊框樣式完整指南:border、cellspacing、cellpadding 與 CSS 邊框模型

HTML 表格邊框與間距控制:從屬性到 CSS 完整遷移

表格邊框與間距控制經歷從 HTML 屬性 (border, cellspacing, cellpadding) 到 CSS 完整接管的演進。理解兩種模型差異,能精準掌控表格視覺呈現。

HTML 屬性時代 (已棄用/不建議)

<table border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td width="200">1</td>
    <td width="200">2</td>
    <td width="200">3</td>
  </tr>
  <tr>
    <td>a</td><td>b</td><td>c</td>
  </tr>
  <tr>
    <td>中國</td><td>我</td><td>愛你</td>
  </tr>
</table>
  • border="1":表格外框與儲存格邊框皆為 1px (雙重邊框)。
  • cellspacing="0":儲存格間距為 0,**關鍵**——否預設 2px 產生雙線效果。
  • cellpadding="0":儲存格內邊距 (內容到邊框) 為 0。

CSS 邊框模型 (現代標準)

<style>
  .modern-table {
    width: 100%;
    border-collapse: collapse; /* 關鍵:合併邊框,等同 cellspacing="0" */
  }
  .modern-table th,
  .modern-table td {
    border: 1px solid #333;    /* 統一邊框樣式 */
    padding: 8px 12px;         /* 等同 cellpadding */
    text-align: left;
  }
  .modern-table th {
    background: #f5f5f5;
    font-weight: 600;
  }
</style>

<table class="modern-table">
  <thead>
    <tr><th>編號</th><th>名稱</th><th>數量</th></tr>
  </thead>
  <tbody>
    <tr><td>1</td><td>產品 A</td><td>100</td></tr>
    <tr><td>2</td><td>產品 B</td><td>200</td></tr>
  </tbody>
</table>

兩種邊框模型差異對比

特性分離邊框模型 (預設 / border-collapse: separate)合併邊框模型 (border-collapse: collapse)
HTML 對應cellspacing="n" (預設 2px)cellspacing="0"
邊框關係相鄰儲存格各有邊框,中間有間隙相鄰儲存格共用單一邊框線
圓角支援支援 border-radius (表格層級)**不支援** border-radius (儲存格層級)
邊框樣式衝突無衝突,各自獨立依優先順序決定:hidden > double > solid > dashed > dotted > ridge > outset > groove > inset > none
效能稍低較高

進階邊框樣式技巧

<style>
  /* 僅外框 */
  .outer-border-only {
    border-collapse: separate;
    border-spacing: 0;
    border: 2px solid #2c3e50;
  }
  .outer-border-only th,
  .outer-border-only td {
    border: none;
    border-bottom: 1px solid #eee;  /* 僅橫線 */
    border-right: 1px solid #eee;   /* 僅直線 */
  }
  .outer-border-only tr:last-child td { border-bottom: none; }
  .outer-border-only tr td:last-child { border-right: none; }

  /* 斑馬紋 */
  .zebra tbody tr:nth-child(even) { background: #f9f9f9; }

  /* 懸浮高亮 */
  .hover-highlight tbody tr:hover { background: #e8f4fd; }
</style>

最佳實務總結

  1. 移除所有 HTML 表格表現屬性 (border, cellspacing, cellpadding, width, align...)。
  2. 預設使用 border-collapse: collapse,簡潔、效能佳、易控制。
  3. 需要圓角表格時,改用 border-collapse: separate + border-spacing: 0 + border-radius 於 <table>。
  4. 邊框顏色、粗細、樣式全由 CSS 定義,支援主題切換、深色模式。
  5. 善用 nth-child、:hover 提升可讀性與互動體驗。

CSS 完全接管表格樣式,是現代前端開發的基本功。

copyright © 萬盛學電腦網 all rights reserved