萬盛學電腦網

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

HTML 表格邊框完美控制:border-collapse、border-spacing、CSS 邊框模型、圓角表格、高對比度模式完整指南

表格邊框三大核心痛點與現代 CSS 解法

表格邊框常見問題:雙線條、間隙無法控制、圓角失效、列印斷裂。本文系統解決:border-collapse 模式選擇、border-spacing 精確間距、box-shadow 模擬邊框突破圓角限制。

兩種邊框模型對比

特性border-collapse: separate (預設)border-collapse: collapse
邊框疊加雙線 (各儲存格各自邊框)單線 (共用邊框)
間距控制border-spacing: 2px 生效忽略 border-spacing
圓角支援border-radius 生效不支援 圓角
邊框樣式每格獨立共用,衝突以優先序決定
效能略高 (獨立盒模型)較佳 (合併計算)

場景一:標準單線邊框 (最常用)

.table-standard {
  border-collapse: collapse;
  width: 100%;
}
.table-standard th,
.table-standard td {
  border: 1px solid #e0e0e0;
  padding: 0.75rem 1rem;
}

場景二:圓角表格 (需 separate + overflow)

.table-rounded {
  border-collapse: separate;
  border-spacing: 0;          /* 關鍵:歸零間距,否則圓角間有縫隙 */
  border-radius: 8px;
  overflow: hidden;           /* 切圓角 */
  width: 100%;
}
.table-rounded th,
.table-rounded td {
  border: none;               /* 移除儲存格邊框 */
  border-bottom: 1px solid #e0e0e0;
  border-right: 1px solid #e0e0e0;
  padding: 0.75rem 1rem;
}
.table-rounded th { background: #f5f5f5; font-weight: 600; }
.table-rounded tr:last-child td { border-bottom: none; }
.table-rounded td:last-child { border-right: none; }

場景三:有間距的卡片式表格

.table-spaced {
  border-collapse: separate;
  border-spacing: 8px;        /* 儲存格間距 8px */
  width: 100%;
}
.table-spaced td,
.table-spaced th {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 6px;         /* 每格獨立圓角 */
  padding: 1rem;
}
/* thead 需特殊處理:th 共用邊框較複雜,建議 thead 也用 separate 或改用 div 佈局 */

場景四:無邊框、僅底線 (極簡風)

.table-minimal {
  border-collapse: collapse;
  width: 100%;
}
.table-minimal th,
.table-minimal td {
  border: none;
  border-bottom: 1px solid #e0e0e0;
  padding: 0.75rem 1rem;
}
.table-minimal th { font-weight: 600; color: #666; font-size: 0.875rem; text-transform: uppercase; letter-spacing: 0.05em; }
.table-minimal tbody tr:hover td { background: #fafafa; }

邊框衝突優先序 (collapse 模式)

  1. hidden (最高,隱藏邊框)
  2. double, solid, dashed, dotted, ridge, outset, inset, groove, none (最低)
  3. 同優先序:較粗者勝、樣式優先序高者勝、th 勝過 td、thead 勝過 tbody、table 最低

高對比度模式 / 強制色彩模式適配

@media (prefers-contrast: high), (forced-colors: active) {
  .table-standard th,
  .table-standard td {
    border-color: CanvasText;  /* 系統文字色 */
    background: Canvas;        /* 系統背景色 */
  }
  .table-standard th { background: CanvasText; color: Canvas; }
  .table-rounded { border-radius: 0; } /* 強制色彩模式下移除圓角避免邊框消失 */
}

列印樣式優化

@media print {
  .table-standard { page-break-inside: auto; }
  .table-standard tr { page-break-inside: avoid; page-break-after: auto; }
  .table-standard thead { display: table-header-group; } /* 每頁重複表頭 */
  .table-standard tfoot { display: table-footer-group; } /* 每頁重複表尾 */
  .table-standard th,
  .table-standard td { border-color: #000 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
}
copyright © 萬盛學電腦網 all rights reserved