網頁中實現虛線效果有多種路徑,各有優劣。本文對比 CSS 原生邊框、背景漸變模擬、圖片填充三大方案,提供選型指南。
/* 1. 直接在元素上設定 */
.dashed-border {
border: 1px dashed #000; /* 虛線邊框 */
}
/* 2. 單向虛線 */
.dashed-bottom {
border-bottom: 2px dashed #ccc;
}
/* 3. 表格虛線邊框(需合併邊框) */
table.dashed { border-collapse: collapse; }
table.dashed td { border-bottom: 1px dashed #ccc; }
優點:代碼極簡、無額外請求、縮放不失真、可動態修改顏色/寬度
缺點:虛線間距/長度不可控、IE6/7 dotted 顯示為方塊、圓角邊框虛線渲染異常
/* 水平虛線:可控長度、間距、顏色、圓角 */
.dashed-custom {
background:
linear-gradient(90deg, currentColor 50%, transparent 50%) repeat-x bottom;
background-size: 10px 2px; /* 虛線長 5px、間距 5px、粗 2px */
padding-bottom: 4px; /* 留空間給背景 */
}
/* 垂直虛線 */
.dashed-vertical {
background:
linear-gradient(180deg, currentColor 50%, transparent 50%) repeat-y right;
background-size: 2px 10px;
padding-right: 4px;
}
/* 矩形虛線框 */
.dashed-box {
background:
linear-gradient(90deg, #ccc 50%, transparent 50%) repeat-x top,
linear-gradient(90deg, #ccc 50%, transparent 50%) repeat-x bottom,
linear-gradient(180deg, #ccc 50%, transparent 50%) repeat-y left,
linear-gradient(180deg, #ccc 50%, transparent 50%) repeat-y right;
background-size: 10px 1px, 10px 1px, 1px 10px, 1px 10px;
}
優點:間距/長度/顏色/圓角完全可控、無圖片請求、矢量不失真
缺點:代碼較複雜、圓角處需額外處理、舊瀏覽器不支持漸變
/* 1x2px 圖片:半透明半透明 */
.dashed-image {
background: url(dashed-1x2.png) repeat-x bottom;
padding-bottom: 2px;
}
/* 表格邊框圖片 */
table.dashed-img {
border-collapse: collapse;
background: url(table-border.png) repeat-y left;
}
table.dashed-img td {
background: url(td-border.png) repeat-x bottom;
}
優點:所有瀏覽器完美一致、複雜圖案可實現
缺點:額外 HTTP 請求、修改顏色需重製圖片、縮放失真、高清屏需多倍圖
| 維度 | CSS Border | 背景漸變 | 圖片填充 |
|---|---|---|---|
| 代碼複雜度 | 極低 | 中等 | 低(但需維護圖片) |
| 可控性 | 低(間距固定) | 極高 | 高(圖片決定) |
| 性能 | 最優 | 優(GPU 加速) | 需圖片請求 |
| 兼容性 | 全瀏覽器(IE6+) | IE10+ / 現代瀏覽器 | 全瀏覽器 |
| 維護成本 | 極低 | 低 | 高(改色改圖) |
border: 1px dashed@supports (background: linear-gradient(...)) 進階增強
<table style="BORDER-LEFT: #000000 1px DASHED; BORDER-RIGHT: #000000 1px DASHED;
BORDER-TOP: #000000 1px DASHED; BORDER-BOTTOM: #000000 1px DASHED">
<tr><td>內容</td></tr>
</table>
⚠️ 僅建議極少量、一次性頁面使用,不可維護。