跳到主要内容

继承

一些 CSS 属性,你如果不指定属性值,会从源头上继承样式。

一个继承的例子:

<html>
<body>
<article>
<p>Lorem ipsum dolor sit amet.</p>
</article>
</body>
</html>
/* 文字会继承 html 的 color */
html {
color: lightslategray;
}

可继承的属性

可见 可继承的属性

  • azimuth

  • border-collapse border-spacing

  • caption-side

  • color

  • cursor

  • direction

  • empty-cells

  • font font-family font-size font-style font-variant font-weight

  • letter-spacing line-height white-space word-spacing

  • list-style-image list-style-position list-style-type list-style

  • orphans

  • quotes

  • text-align text-indent text-transform

  • visibility

  • widows

继承的工作原理

  1. 每个元素的所有 CSS 属性在一开始会有一个初始值(非继承)。

  2. 元素里可以被继承的属性会向下应用到子元素。

  3. 元素已有的属性会覆盖继承到的属性。

​​非可继承的属性可以用 inherit 值来继承。 可继承的属性可以用 initial 值来设定为默认值。 以上两种情况等价于使用 unset 值。

可以用 all: unset 来应用于所有属性,此举会覆盖别的属性的 unset 行为,但是可以给定值(在 all 属性上声明也会无效)。


参考

Inheritance,Learn CSS - web.dev

计算值 - MDN