Css Reset 有各種叫法——「CSS 復位」「默認樣式重置」等等。讀完本文,你大概會對它有個新的認識。
各瀏覽器對 CSS 規則的默認實現並不相同:同一個 h1 在不同瀏覽器下的 margin 可能有幾像素差異,ul 的左側內距也不一致。這些差異會讓「在 IE 裡正常、到 Firefox 裡就變形」成為日常。Reset 的目的就是抹平原生差異,建立一個可預期的起點,某種程度上確實能節省時間與返工成本。
* {
padding: 0;
margin: 0;
}
這段代碼到處可見,但問題也最多——它會把所有元素的間距清零,包括段落、列表、標題,後續你得逐一重新定義。
版本二加入了 border: 0:
* { padding: 0; margin: 0; border: 0; }
這已經不太靠譜了——很多組件(表單控件、圖片鏈接)依賴默認邊框,一刀切清零後需要大量補救。
版本三再加 outline: 0:
* { outline: 0; padding: 0; margin: 0; border: 0; }
更不推荐。outline 承擔著鍵盤導航的焦點提示,去掉它會直接損害可訪問性。
這是一種相對周全的寫法,通過 inherit 讓字體屬性回歸父級,從而在各浏覽器間取得一致性:
* {
vertical-align: baseline;
font-weight: inherit;
font-family: inherit;
font-style: inherit;
font-size: 100%;
border: 0 none;
outline: 0;
padding: 0;
margin: 0;
}
只處理最關鍵的幾處,對字號做復位,並去掉圖片鏈接的邊框:
html, body {
padding: 0;
margin: 0;
}
html { font-size: 1em; }
body { font-size: 100%; }
a img, :link img, :visited img { border: 0; }
這類寫法侵入性小,在很多項目中直接沿用也沒問題。
這一套有明確的目的性,針對主流瀏覽器(IE、Firefox 等)逐一列舉元素:
body, div, dl, dt, dd, ul, ol, li,
h1, h2, h3, h4, h5, h6, pre,
form, fieldset, input, p, blockquote, table, th, td, embed, object {
padding: 0;
margin: 0;
}
table { border-collapse: collapse; border-spacing: 0; }
fieldset, img, abbr { border: 0; }
address, caption, cite, code, dfn, em,
h1, h2, h3, h4, h5, h6, strong, th, var {
font-weight: normal;
font-style: normal;
}
ul { list-style: none; }
caption, th { text-align: left; }
h1, h2, h3, h4, h5, h6 { font-size: 1.0em; }
q:before, q:after { content: ''; }
a, ins { text-decoration: none; }
Yahoo 的這一份在權衡上做得比較克制,值得推薦:
body, div, dl, dt, dd, ul, ol, li,
h1, h2, h3, h4, h5, h6, pre, form,
fieldset, input, textarea, p, blockquote, th, td {
padding: 0;
margin: 0;
}
table { border-collapse: collapse; border-spacing: 0; }
fieldset, img { border: 0; }
address, caption, cite, code, dfn, em, strong, th, var {
font-weight: normal;
font-style: normal;
}
ol, ul { list-style: none; }
caption, th { text-align: left; }
h1, h2, h3, h4, h5, h6 {
font-weight: normal;
font-size: 100%;
}
q:before, q:after { content: ''; }
abbr, acronym { border: 0; }
Reset 本質上是一場取捨:重置得越徹底,起點越統一,但要補回的樣式也越多。一個實用原則是——只重置你項目中真正會用到的元素,並保留 outline 以不破壞鍵盤可訪問性。把 Reset 當作項目的起點而非教條,按需增刪,才是最務實的做法。