虛線在網頁設計中無所不在,從邊框、連結下劃線到清單分隔線都用得上。本文系統整理以 CSS 製作虛線的各種方法。
透過 border 屬性的 dashed 樣式即可控制虛線(以下寬高設為 350px 是為了方便觀察)。
一、四邊虛線:border:1px dashed #000; 為黑色虛線邊框。
CSS:.poluoluo{border:1px dashed #000; height:50px;width:350px}
HTML:<div class="poluoluo">我的四邊為黑色虛線邊框</div>
二、左邊虛線:CSS:.poluoluo-1{border-left:1px dashed #000; height:50px;width:350px}
HTML:<div class="poluoluo-1">我的左邊為黑色虛線邊框</div>
三、右邊虛線:CSS:.poluoluo-2{border-right:1px dashed #000; height:50px;width:350px}
HTML:<div class="poluoluo-2">我的右邊為黑色虛線邊框</div>
四、頂部虛線:CSS:.poluoluo-3{border-top:1px dashed #000; height:50px;width:350px}
HTML:<div class="poluoluo-3">我的上邊為黑色虛線邊框</div>
五、底部虛線:CSS:.poluoluo-4{border-bottom:1px dashed #000; height:50px;width:350px}
HTML:<div class="poluoluo-4">我的下邊為黑色虛線邊框</div>
六、三邊虛線、一邊無框線:CSS:.poluoluo-5{border:1px dashed #000;border-right:0; height:50px;width:350px}
先設四邊虛線,再把其中一邊設為 0,即可只保留三邊。注意邊框設定的先後順序會影響結果。
完整範例:
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>CSS 虛線範例</title>
<style>
.poluoluo{ border:1px dashed #000; height:50px; width:350px}
.poluoluo-1{border-left:1px dashed #000; height:50px;width:350px}
.poluoluo-2{border-right:1px dashed #000; height:50px;width:350px}
.poluoluo-3{border-top:1px dashed #000; height:50px;width:350px}
.poluoluo-4{border-bottom:1px dashed #000; height:50px;width:350px}
.poluoluo-5{border:1px dashed #000; border-right:0;height:50px;width:350px}
</style>
</head>
<body>
<div class="poluoluo">我四邊為虛線邊框</div><br>
<div class="poluoluo-1">我的左邊為黑色虛線邊框</div><br>
<div class="poluoluo-2">我的右邊為黑色虛線邊框</div><br>
<div class="poluoluo-3">我的上邊為黑色虛線邊框</div><br>
<div class="poluoluo-4">我的下邊為黑色虛線邊框</div><br>
<div class="poluoluo-5">我的右邊無框線而其他三邊為虛線</div>
</body>
</html>
一、連結文字自帶虛線下劃線:同樣透過 border 控制 a 元素:
a{ border-bottom:1px dashed #111;}/* 下方出現虛線 */
a:hover{ border:0;}/* 滑鼠移過時不顯示 */
完整範例:
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>CSS 虛線下劃線範例</title>
<style>
a{ border-bottom:1px dashed #111;text-decoration:none;}
a:hover{ border:0;}
</style>
</head>
<body>
歡迎來到 <a href="https://www.poluoluo.com/">CSS 教程網</a>
</body>
</html>
說明:text-decoration:none; 用來移除連結預設的下劃線。
二、滑鼠移過時才出現虛線下劃線:把上面兩條規則對調即可:
a{text-decoration:none;}
a:hover{border-bottom:1px dashed #111;}
常有人希望 li 清單每一列下方以虛線分隔。只要為 li 設定底部虛線邊框即可:
li{border-bottom:1px dashed #111;}
若想要的虛線極細(細如一個點),border 就難以勝任,此時可改用一張虛線點圖(1px 高、3px 寬的純色圖即可):
Li{background:url(點圖片路徑) repeat-x 0 bottom}
用 div 設定底部虛線邊框,或直接用 hr 標籤,都能做出水平分隔線。
對 div 設定:
.poluoluo{ height:1px; width:100%; border-bottom:1px dashed #000;}
HTML:<div class="poluoluo"></div>
對 hr 設定,第一種直接在標籤內寫:
<hr size=1 style="color: blue;border-style:dashed ;width:100%">
第二種在 CSS 中定義 hr 樣式:
hr {border-top:1px dashed #00F ; }
HTML:<hr size=1>
兩者效果相近,唯一差別在於後者可被多處重複引用、減少程式碼量。掌握以上方法,你就能靈活製作各種虛線邊框、虛線下劃線與分隔線。