初始值和未设置值之间的区别是什么?

举个简单的例子:

超文本标示语言

<p style="color:red!important">
this text is red
<em>
this text is in the initial color (e.g. black)
</em>
this is red again
</p>

CSS

em {
color:initial;
color:unset;
}

initialunset有什么区别? 只支持浏览器

CanIUse: CSS 取消设置值

开发人员 Mozilla Web CSS 初始化

67976 次浏览

根据 你的链接:

unset是一个 CSS 值,如果一个属性是继承的,它与“继承”相同; 如果一个属性不是继承的,它与“初始”相同

这里有一个例子:

pre {
color: #f00;
}
.initial {
color: initial;
}
.unset {
color: unset;
}
<pre>
<span>This text is red because it is inherited.</span>
<span class="initial">[color: initial]: This text is the initial color (black, the browser default).</span>
<span class="unset">[color: unset]: This text is red because it is unset (which means that it is the same as inherited).</span>
</pre>

A scenario where the difference matter is if you are trying to override some CSS in your stylesheet, but you would prefer the value is inherited rather than set back to the browser default.

例如:

pre {
color: #00f;
}
span {
color: #f00;
}
.unset {
color: unset;
}
.initial {
color: initial;
}
<pre>
<em>Text in this 'pre' element is blue.</em>
<span>The span elements are red, but we want to override this.</span>
<span class="unset">[color: unset]: This span's color is unset (blue, because it is inherited from the pre).</span>
<span class="initial">[color: initial]: This span's color is initial (black, the browser default).</span>
</pre>

我想引用官方的 CSS | MDN 文档,以备将来在研究两者之间的差异时参考:

首字母缩写

初始 CSS 关键字将属性的初始值应用于元素。它允许在每个 CSS 属性上使用,并导致为其指定的元素使用该属性的初始值。

因此,根据你的例子:

em {
color:initial;
/* color:unset; */
}
<p style="color:red!important">
this text is red
<em>
this text is in the initial color (e.g. black)
</em>
this is red again
</p>

请注意 首字母缩写属性如何保留元素的 首字母缩写color属性。

未开始

Unset CSS 关键字是初始关键字和继承关键字的组合。像这两个 CSS 范围的关键字一样,它可以应用于任何 CSS 属性,包括 CSS 的简写 all。此关键字将属性重置为其继承的值(如果它从其父级继承) ,或重置为其初始值(如果不是)。换句话说,在第一种情况下,它的行为类似继承关键字,在第二种情况下,它的行为类似初始关键字。

Therefore according to your example:

em {
/* color:initial; */
color:unset;
}
<p style="color:red!important">
this text is red
<em>
this text's color has been unset (e.g. red)
</em>
this is red again
</p>

Note how the unset property simply 重置 the color property of the element.

结论

这个想法很简单,但是在实践中,我建议在处理 CSS 属性的跨浏览器兼容性时要小心。

CSS 显示属性: 取消设置 = 继承