<hr> 預設樣式相當樸素,而且各瀏覽器之間落差明顯。只要把預設邊框清掉、改用 border-top 畫線,就能自由控制粗細、顏色與線條風格。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="zh" lang="zh-Hant">
<head>
<title>hr 樣式變化</title>
<style type="text/css">
.hr0 { height: 1px; border: none; border-top: 1px dashed #1E90FF; }
.hr1 { height: 1px; border: none; border-top: 1px solid #000; }
.hr2 { height: 3px; border: none; border-top: 3px double #6B8E23; }
.hr3 { height: 5px; border: none; border-top: 5px ridge #45D6D8; }
.hr4 { height: 10px; border: none; border-top: 10px groove #FF8C00; }
</style>
</head>
<body>
<hr class="hr0" />
<hr class="hr1" />
<hr class="hr2" />
<hr class="hr3" />
<hr class="hr4" />
</body>
</html>
border: none 必須寫在 border-top 之前。由於兩者發表在同一個規則裡,後者會覆蓋前者的上邊框部分,因此順序寫錯就會前功盡棄。
height 要與 border 粗細對應。這裡刻意讓兩者數值相同,是為了讓元素的高度與視覺上的線條一致。若 height 設得比 border 小,線條會溢出元素的內容框,在 margin 計算上產生意料之外的間距。
顏色決定線條的個性。deep pink、橄欖綠、青藍、暗橙——同一個 solid 換個顏色就是完全不同的語氣,這比調整粗細更容易改變整體氛圍。
CSS 的 border-style 提供 dashed(虛線)、dotted(點線)、solid(實線)、double(雙線)、groove(槽線,凹入感)、ridge(脊線,凸起感)、inset(內凹)、outset(外凸)等選項。其中 groove 與 ridge 是靠上下兩色明暗差來製造立體感,因此 粗細至少要 3px 以上才看得出效果,1px 的 groove 看起來就跟 solid 差不多。
用 background 畫線可以避開 border 相關的一切牽扯:
.hr5 {
border: 0;
height: 1px;
background: #1E90FF;
margin: 20px 0;
}
這種寫法在 box-sizing 調整、CSS reset 或栅格系統共存的環境下更可控,因為它完全不依賴邊框。若希望間距由 margin 統一管理,也可以考慮直接拿掉 hr,改用一個帶 border-top 的空 div,讓樣式表裡的分割線有一致的行為。