不要继承盒模型

At the most basic, a modern CSS ‘reset’ will often start with one of the following:

最基础的现代 CSS “重置”通常以以下代码开头:


* { box-sizing: border-box; } html { box-sizing: border-box; }
* { box-sizing: inherit; }

Each one has a variant that includes *::before, *::after along side the universal selector. That’s because * itself only selects actual elements, not pseudo-elements like ::before and ::after. We’ll get to that, but first let’s talk about inheriting the box model.

每个方案都有一个包含 *::before, *::after 的变体,与通用选择器并列。这是因为 * 本身只选中实际元素,而不选中像 ::before::after 这样的伪元素。我们稍后会讲到,但先谈谈盒模型的继承。

While inheritance is a core concept in CSS, only a small minority of properties ever do it. Inheritance is part of the ‘defaulting’ process, which determines what to do when no value has been explicitly provided for a given property on a given element. Some properties, like color and font revert to the value used on the parent element. They inherit the value. But most of the properties we use – background, border, margin, padding, display, and so on – revert instead to their initial value defined in the specification.

虽然继承是 CSS 的核心概念,但只有极少数属性会真正继承。继承属于“默认值”流程的一部分,用于决定在某一元素上未显式提供值时该怎么做。像 colorfont 这样的属性会回退到父元素使用的值,它们会继承该值。但我们使用的大多数属性——backgroundbordermarginpaddingdisplay 等——则会回退到规范中定义的初始值。

There are more properties in each category, but I think at this point the distinction should be clear. Some properties apply to the contents, and those are the properties that inherit. Other properties apply to the box, and do not inherit.

每个类别里还有更多属性,但我认为此时区别已经很清楚了。有些属性作用于内容,因此会继承;另一些属性作用于盒子,因此不会继承。

Generally your instinct will tell you which is which. If you add a random span somewhere in a line of text, which properties would need to inherit in order for that span to remain un-styled by default? If the font-size or color of the text reset to their initial values (medium and CanvasText), that would be a noticeable change in styles. But if a border and background were added to match the parent box, that would be even more noticeable!

通常你的直觉会告诉你哪个是哪个。如果你在...

开通本站会员,查看完整译文。

Home - Wiki
Copyright © 2011-2025 iteam. Current version is 2.146.0. UTC+08:00, 2025-09-12 01:37
浙ICP备14020137号-1 $Map of visitor$