一个简单的例子:
HTML
<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;
}
initial
和unset
之间有什么区别?仅支持浏览器
答案 0 :(得分:50)
将我的评论移至答案
根据your link:
unset
是一个CSS值,它与&#34;继承&#34;相同。如果财产是继承的或&#34;初始&#34;如果属性未被继承
以下是一个例子:
pre {
color: #f00;
}
.initial {
color: initial;
}
.unset {
color: unset;
}
&#13;
<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>
&#13;
如果您尝试覆盖样式表中的某些CSS,那么差异很重要,但您希望继承该值而不是设置回浏览器默认值。
例如:
pre {
color: #00f;
}
span {
color: #f00;
}
.unset {
color: unset;
}
.initial {
color: initial;
}
&#13;
<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>
&#13;
答案 1 :(得分:1)
我想引用官方的CSS | MDN文档,以便在查看每个文档之间的差异时将来参考:
<强> INITIAL 强>
初始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关键字是initial和inherit关键字的组合。与其他两个CSS范围的关键字一样,它可以应用于任何CSS属性,包括CSS简写全部。如果该属性从其父级继承,则将该属性重置为其继承的值,否则重置为其初始值。换句话说,它的行为类似于第一种情况下的inherit关键字,就像第二种情况下的initial关键字一样。
因此根据你的例子:
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>
注意 unset 属性如何重置元素的color
属性。
结论
这个想法很简单,但在实践中,我会建议在处理两个CSS属性的跨浏览器兼容性时要谨慎......就像今天这样。