CSS: Reset

 20th August 2020 at 2:19pm

CSS Reset 是指一套样式表,它的目标是将 User Agent 默认的样式表覆盖,用来提供一个 UA 无关的样式表。

CSS Reset 的 idea 最早是 Meyer's reset 发扬光大的。现在比较流行的是:

necolas 和 csstools 的同名 normalize.css 项目,一开始是共同开发的,后来分开维护了。csstools 的作者 讲述 了其中的区别:

  • The necolas version includes non-fixes, previously known as opinionated defaults before such documentation was removed, like body { margin: 0 }.
  • The csstools version is more actively maintained.
  • I am blocked from submitting PRs or following any changes or discussions in the necolas version.

csstools 的 normalize.css 和 sanitize.css 区别在于:

normalize.css and sanitize.css correct browser bugs while carefully testing and documenting changes. normalize.css styles adhere to css specifications. sanitize.css styles adhere to common developer expectations and preferences. reset.css unstyles all elements. Both sanitize.css and normalize.css are maintained in sync.

同时 csstools 还提供了很多额外的工具帮你写出好的 CSS。

A look at CSS Resets in 2018 是一篇用于理解 CSS reset 的非常好的文章。它讲述了 CSS reset 三个最主要的功能:

  • Correct user agent styling errors
  • Undo any "opinionated" user agent styling
  • Create a consistent, largely opinionated, style base

有些框架会把一些合理的默认样式覆盖掉,以方便框架自己定义自己的一套,比如 Bulma

  • <h1><h6>font-size 全部重置成了 100%,再自己定义的 font-size 大小
  • <button> <input> 等控件的 margin 全部置成了 0,再自己定义 margin 大小

CSS 框架都会做 CSS Reset,如 BootstrapBulma。普通的网站项目建议用 normalize.css。

Typical reset

典型的 reset 点。

box-sizing reset

CSS Reset 中一般有一项是 box-sizing 置为 border-box(而不是 content-box,原因参考 CSS: Layout: Box Model):

*,
*::before,
*::after {
  box-sizing: border-box;
}

对于为什么需要 *::before*::after,是因为他们是唯二可以往页面中插入内容的 pseudo-elements,所以需要选中它们所插入进来的元素。参考 CSS: Selector

如果你在工程中使用了上述 CSS,而你所使用的一些第三方 CSS 库仍然在使用 content-box,那这种写法会引起问题。你可以换成这种写法:

/* :root 在浏览器环境中即 html */
:root {
  box-sizing: border-box;
}

*,
*::before,
*::after {
  box-sizing: inherit;
}

/* 
 * 对于使用了 content-box 的组件,在它的上层 container 中设置 box-sizing。
 * 这样不用对它的每个元素都做设置。
 */
.third-party-component {
  box-sizing: content-box;
}

Resources