| 方案 | 原理 | 相容性 | 維護性 | 推薦指數 |
|---|---|---|---|---|
| 背景圖片模擬 | 1x2px 半透明圖片 repeat-x/y | 全瀏覽器(含 IE6) | 差(修改顏色需改圖) | ⭐⭐ |
CSS border-style: dashed | 原生虛線渲染 | IE5.5+、全現代瀏覽器 | 優(純代碼控制) | ⭐⭐⭐⭐ |
| SVG/Canvas 繪製 | 矢量/位圖程式化繪製 | IE9+、現代瀏覽器 | 中(需 JS 支援) | ⭐⭐⭐(複雜圖案) |
/* 完整寫法 */
.dashed-border {
border-width: 1px;
border-style: dashed; /* 關鍵屬性 */
border-color: #000;
/* 或縮寫 */
border: 1px dashed #000;
}
/* 單邊虛線 */
.border-top-only { border-top: 2px dashed red; }
.border-bottom-only { border-bottom: 1px dashed #ccc; }
IE5.5/6/7 時代遺留問題:
dashed 渲染為實線(需 border-width ≥ 2px 才顯示虛線)dotted 顯示為方塊而非圓點border-collapse: collapse 導致虛線斷裂現代策略:直接使用標準語法,透過 @supports 或 Polyfill 處理極少數舊環境。
table.dashed {
border-collapse: collapse; /* 關鍵:合併邊框 */
border: 1px dashed #ccc;
}
table.dashed td,
table.dashed th {
border: 1px dashed #ccc;
padding: 8px;
}
.divider {
height: 0;
border-top: 1px dashed #e0e0e0;
margin: 1rem 0;
}
/* 帶文字的分隔線 */
.divider-with-text {
display: flex;
align-items: center;
text-align: center;
color: #999;
font-size: 0.875rem;
}
.divider-with-text::before,
.divider-with-text::after {
content: '';
flex: 1;
border-top: 1px dashed currentColor;
}
.divider-with-text::before { margin-right: 1rem; }
.divider-with-text::after { margin-left: 1rem; }
@keyframes dash-draw {
to { stroke-dashoffset: -100; }
}
.animated-dashed {
border: 2px dashed transparent;
background: linear-gradient(white, white) padding-box,
repeating-linear-gradient(45deg, #007bff, #007bff 10px, transparent 10px, transparent 20px) border-box;
animation: dash-move 1s linear infinite;
}
@keyframes dash-move {
to { background-position: 20px 0; }
}
--color-border-muted.divider、.border-dashed、.focus-ring-dashed現代 CSS 開發中,原生 border-style: dashed 結合邏輯屬性(border-inline-start 等)是首選方案,僅在極特殊圖案需求下考慮 SVG/Canvas。