<hr> 在不同瀏覽器下的預設樣式差異不小,最常見的困擾是它上下會帶入一塊說不上來的空白。IE 對 hr 的 margin 處理尤其我行我素,導致同一份程式碼在 IE 與其他瀏覽器中的間距完全不同。
思路是:先把 hr 的邊框全部關掉,改用 border-top 畫出線條,再用 *margin 這個只有 IE 認得的 Hack 把多餘的間距抵銷掉。
<!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">
* { margin: 0; padding: 0; }
body {
font: 12px/130% Verdana, Geneva, Arial, Helvetica, sans-serif, "新細明體";
text-align: center;
}
li { list-style: none; }
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix { display: inline-block; }
.hr1 {
height: 1px;
border: none;
border-top: 1px solid Black;
margin: 0;
*margin: 0 0 -14px 0;
float: none;
*float: left;
display: block;
}
.hr2 {
height: 2px;
border: none;
border-top: 2px solid #C71585;
margin: 0;
*margin: 0 0 -14px 0;
float: none;
*float: left;
display: block;
}
.hr3 {
height: 3px;
border: none;
border-top: 3px solid #6B8E23;
margin: 0;
*margin: 0 0 -14px 0;
float: none;
*float: left;
display: block;
}
div { height: 20px; background: #D3EDF8; }
</style>
</head>
<body>
<div></div>
<hr class="hr1" />
<hr class="hr2" />
<hr class="hr3" />
<div></div>
</body>
</html>
border: none 加上 border-top:hr 本身預設帶有立體感的邊框,全部清掉之後只留一條上邊線,線條粗細與顏色就完全由你決定。height 對應邊框的粗細,兩者要一起設定。
*margin: 0 0 -14px 0:星號前綴只有 IE 6 及更早版本認得,因此這條只作用於需要修正的那個環境。負的下邊距把 IE 額外產生的空白往下收,讓視覺間距與其他瀏覽器一致。實際要補多少像素,得依你的行高與上下文調整,這裡的 −14px 是配合 line-height: 130% 的實測值。
*float: left:IE 對 hr 的區塊高度計算有 bug,讓它浮動可以強迫它依 height 收縮,而不是沿用預設的高度。其他瀏覽器讀的是 float: none,不受影響。
如果專案不必理會舊版 IE,那麼整段可以簡化成:
hr {
border: 0;
height: 1px;
background: #000;
margin: 20px 0;
}
用 background 畫線比用 border 更可控,因為它不會受 box-sizing 與 border 相關規則的牽動。真想避開所有跨瀏覽器差異,也可以直接拿掉 hr,改用一個設了 border-top 的空 div,樣式完全由自己定義。