CSS Reset 的價值在於抹平各瀏覽器的預設樣式差異。本文繼續看兩套實用的 reset 腳本,並分析它們的取捨。
這套的特點是把 font 相關屬性全部「歸零再重建」——font-weight、font-style 設為 normal,font-family 設為 inherit,讓字型完全交由後續規則決定:
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p,
blockquote, pre, a, abbr, acronym, address, big,
cite, code, del, dfn, em, font, img,
ins, kbd, q, s, samp, small, strike,
strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
center, u, b, i {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: normal;
font-style: normal;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
}
body { line-height: 1; }
:focus { outline: 0; }
ol, ul { list-style: none; }
table { border-collapse: collapse; border-spacing: 0; }
blockquote:before, blockquote:after, q:before, q:after { content: ""; }
blockquote, q { quotes: "" ""; }
input, textarea { margin: 0; padding: 0; }
hr {
margin: 0;
padding: 0;
border: 0;
color: #000;
background-color: #000;
height: 1px;
}
值得注意的三處:body{line-height:1} 統一了行高基準;:focus{outline:0} 移除了焦點虛線框(但這會傷害鍵盤無障礙,建議改用 :focus-visible 精準處理);hr 用背景色加高度重畫,因為各瀏覽器對 hr 的預設樣式差異極大。
這套差異不大,但多處理了幾個實務細節:
html, body, div, span, applet, object, iframe, h1, h2, h3,
h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address,
big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend, table, caption, tbody, tfoot,
thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: inherit;
font-style: inherit;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
}
:focus { outline: 0; }
table { border-collapse: separate; border-spacing: 0; }
caption, th, td { text-align: left; font-weight: normal; }
a img, iframe { border: none; }
ol, ul { list-style: none; }
input, textarea, select, button {
font-size: 100%;
font-family: inherit;
}
select { margin: inherit; }
/* 修正 IE6/7 中 ol 編號位置錯誤 */
ol { margin-left: 2em; }
/* clearfix */
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix { display: inline-block; }
* html .clearfix { height: 1%; }
.clearfix { display: block; }
它比 AnIE2K 多做了三件事:把表單元素(input、textarea、select、button)的 font 屬性一起歸一,避免表單在 Safari 下字型與頁面不一致;修正 IE6/7 的清單編號位置;以及內附 clearfix 工具類。
選擇器列表越長,reset 越徹底,但檔案也越大。前面看過的 Yahoo YUI 版本走的是精簡路線——只重設真正有差異的屬性,不追求全面歸零。這在大規模網站上更合適,因為每一次額外的樣式宣告都是頻寬。
如果今天要挑一套,其實不必從這些老腳本裡選。現行方案是 Modern CSS Reset 這類現代版本,它會保留有意義的預設值(例如 <ul> 的 list-style 在無障礙場景下有實際功能),並改用 box-sizing: border-box 統一計算方式。更根本的做法是使用 Tailwind 的 Preflight 或 Normalize.css——後者選擇「修正差異」而非「全部歸零」,保留了語意元素該有的樣式。