萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS Reset 完全指南:為何不建議全域重置,主流方案怎麼選?

什麼是 CSS Reset?為什麼需要它?

各瀏覽器對 HTML 元素有不同的預設樣式(user agent stylesheet),例如 body 有 margin、ul 有 padding-left、h1-h6 字體大小不同。CSS Reset 旨在「歸零」這些差異,建立一致的跨瀏覽器基準。

❌ 避免使用:全域選擇器重置

* { margin: 0; padding: 0; }

缺點:

  • 效能差:瀏覽器需遍歷所有元素
  • 副作用大:連 input、button、select 等表單元素也被重置,導致原生外觀消失,需大量補回
  • 破壞預設行為:如 ul/ol 失去縮排、sup/sub 失去垂直對齊

✅ 推薦方案一:Eric Meyer Reset 2.0(經典歸零)

/* https://meyerweb.com/eric/tools/css/reset/ v2.0 */
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, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline;
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; }
body { line-height: 1; }
ol, ul { list-style: none; }
blockquote, q { quotes: none; }
blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; }
table { border-collapse: collapse; border-spacing: 0; }

✅ 推薦方案二:YUI Reset / Normalize.css(現代保留有用預設)

Normalize.css 不盡歸零,而是:

  • 保留有用的瀏覽器預設(如 sup/sub、input 聚焦樣式)
  • 修正常見瀏覽器 Bug(如 audio:not([controls]) 隱藏、button 字體繼承)
  • 模組化、文檔完善、易於客製化
/* 安裝方式 */
npm install normalize.css
/* 或 CDN */
@import url('https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css');

專案級 Reset 建議配置

/* 1. 引入 Normalize.css */
@import 'normalize.css';

/* 2. 專案通用基礎樣式 */
:root {
  --font-base: 16px;
  --line-height-base: 1.5;
}
html { font-size: var(--font-base); }
body { 
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans TC", sans-serif;
  line-height: var(--line-height-base);
  color: #212529;
  -webkit-font-smoothing: antialiased;
}
img, video { max-width: 100%; height: auto; display: block; }
a { color: inherit; text-decoration: none; }
button, input, select, textarea { font: inherit; color: inherit; }

如何選擇適合專案的方案?

專案類型建議方案理由
傳統企業官網、後台管理Eric Meyer Reset完全控制、無預設干擾
現代響應式網站、元件庫Normalize.css保留語意、無障礙友善、維護成本低
極簡專案、單頁面自訂輕量 Reset僅歸零必要屬性,體積最小

延伸閱讀

奠定基礎樣式後,建議學習 CSS 下拉選單實作技巧,打造互動式導覽介面。

copyright © 萬盛學電腦網 all rights reserved