萬盛學電腦網

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

打造美觀 HTML 表格:CSS 樣式技巧與響應式設計實戰

傳統 HTML 表格預設外觀單調,現代網頁設計透過 CSS 即可實現美觀、可讀性高且響應式的表格。本文提供實用的 CSS 樣式模組,涵蓋邊框合併、斑馬紋、懸停高亮、響應式捲動、固定表頭等技巧,並附上可直接套用的完整程式碼範例。

基礎重置與結構

<table class="styled-table">
  <thead>
    <tr><th>產品</th><th>價格</th><th>庫存</th><th>狀態</th></tr>
  </thead>
  <tbody>
    <tr><td>筆記型電腦</td><td>$25,000</td><td>12</td><td>有貨</td></tr>
    <tr><td>滑鼠</td><td>$500</td><td>50</td><td>有貨</td></tr>
    <tr><td>鍵盤</td><td>$1,200</td><td>8</td><td>缺貨</td></tr>
  </tbody>
  <tfoot>
    <tr><td colspan="3">總計</td><td>3 項</td></tr>
  </tfoot>
</table>

核心 CSS 模組

/* 1. 基礎美觀:邊框合併、內距、字體 */
.styled-table {
  border-collapse: collapse;        /* 合併邊框,避免雙線 */
  width: 100%;
  max-width: 800px;
  margin: 1rem auto;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  font-size: 0.95rem;
  line-height: 1.5;
  color: #333;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  border-radius: 8px;
  overflow: hidden;                 /* 配合 border-radius 裁切邊角 */
}

.styled-table th,
.styled-table td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

/* 2. 表頭樣式 */
.styled-table thead th {
  background: linear-gradient(135deg, #2c3e50 0%, #1a252f 100%);
  color: #fff;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  border-bottom: 2px solid #34495e;
}

/* 3. 斑馬紋(隔行變色) */
.styled-table tbody tr:nth-child(even) {
  background-color: #f8f9fa;
}

/* 4. 懸停高亮 */
.styled-table tbody tr:hover {
  background-color: #e8f4fd;
  transition: background-color 0.2s ease;
}

/* 5. 狀態欄位顏色區分 */
.styled-table td.status-available { color: #27ae60; font-weight: 500; }
.styled-table td.status-out { color: #e74c3c; font-weight: 500; }

/* 6. 響應式:小螢幕橫向捲動 */
@media (max-width: 600px) {
  .styled-table {
    display: block;
    overflow-x: auto;
    white-space: nowrap;
    border-radius: 0;
  }
  .styled-table thead { display: table-header-group; }
  .styled-table tbody { display: table-row-group; }
}

/* 7. 固定表頭(需容器限制高度) */
.table-wrapper {
  max-height: 300px;
  overflow-y: auto;
}
.sticky-header thead th {
  position: sticky;
  top: 0;
  z-index: 1;
  background: #2c3e50; /* 需指定實體背景色,避免透明穿透 */
}

進階技巧

欄寬自適應與固定

.styled-table th:nth-child(1) { width: 40%; min-width: 150px; }
.styled-table th:nth-child(2) { width: 20%; }
.styled-table th:nth-child(3) { width: 20%; }
.styled-table th:nth-child(4) { width: 20%; }

載入狀態骨架屏

.styled-table.skeleton tbody tr {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}
@keyframes shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

列點擊展開詳情

<tr class="expandable" data-detail="detail-row-1">...</tr>
<tr id="detail-row-1" class="detail-row" hidden>
  <td colspan="4">詳細資訊內容...</td>
</tr>


						
copyright © 萬盛學電腦網 all rights reserved