萬盛學電腦網

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

CSS 實現表格虛線邊框:border-style 精準控制

表格默認實線邊框通過 border-style: dashed 輕鬆轉為虛線。結合 border-collapse 控制邊框合併,實現精美的虛線表格效果。

核心代碼

<style>
.table-dashed {
  width: 650px;
  border: 1px solid #ccc;       /* 外邊框實線 */
  border-radius: 3px;
  background: #fff;
  border-collapse: collapse;    /* 關鍵:合併邊框,避免雙線 */
}

.table-dashed td {
  border-bottom: 1px dashed #ccc;  /* 內部橫向虛線 */
  padding: 8px 12px;
}

.table-dashed tr.last td {
  border-bottom: none;            /* 最後一行無底線 */
}
</style>

<table class="table-dashed">
  <tr><td colspan="4">&nbsp;</td></tr>
  <tr>
    <td>項目一</td>
    <td>內容描述內容描述</td>
    <td>詳情</td>
    <td>2023.01.20</td>
  </tr>
  <tr class="last">
    <td>項目二</td>
    <td>另一內容</td>
    <td>詳情</td>
    <td>2023.01.20</td>
  </tr>
</table>

關鍵屬性解析

屬性 值 效果
border-style dashed 虛線(方形點)
dotted 點線(圓形點,IE6/7 顯示為方塊)
solid 實線(默認)
double 雙實線
border-collapse collapse 合併相鄰邊框為單線(關鍵)
separate 分離邊框(默認,雙線效果)

進階:虛線間距與顏色控制

原生 dashed 間距不可控,若需自定義虛線樣式:

方案一:背景圖片模擬(完全可控)

.custom-dashed td {
  background: 
    linear-gradient(90deg, #ccc 50%, transparent 50%) repeat-x bottom,
    linear-gradient(90deg, #ccc 50%, transparent 50%) repeat-x top;
  background-size: 10px 1px;  /* 虛線長 5px、間距 5px */
  padding-bottom: 2px;        /* 留空間給背景 */
}

方案二:SVG 背景(矢量不失真)

.svg-dashed td {
  background: url("data:image/svg+xml,%3Csvg xmlns='https://www.w3.org/2000/svg' width='10' height='1'%3E%3Cline x1='0' y1='0.5' x2='5' y2='0.5' stroke='%23ccc' stroke-width='1'/%3E%3C/svg%3E") repeat-x bottom;
}

方案三:HR 分割線替代表格邊框

.div-table .row { display: flex; padding: 8px 0; }
.div-table .row:not(:last-child)::after {
  content: "";
  flex: 1;
  border-bottom: 1px dashed #ccc;
  margin: 0 12px;
}

避坑指南

  • ❌ 直接給 table 設 border: 1px dashed → 單元格間會出現雙線
  • ✅ 使用 border-collapse: collapse 合併邊框
  • ✅ 單元格僅設單向邊框(如 border-bottom),避免重疊
  • ✅ 最後一行通過類名移除底線
  • ✅ IE6/7 dotted 顯示為方塊,虛線 dashed 表現正常
copyright © 萬盛學電腦網 all rights reserved