初始值和未设置值有什么区别?


86

一个简单的例子:

的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?仅支持浏览器

CanIUse:CSS未设置值

开发人员Mozilla Web CSS初始

Answers:


108

根据您的链接

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>

如果您想覆盖样式表中的某些CSS,但您更希望该值是继承的,而不是设置回浏览器的默认值,那么情况就很不同。

例如:

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>


7

在研究两者之间的差异时,我想引用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元素的属性。

取消设定

未设置CSS关键字是initial关键字和Inherited关键字的组合。像其他两个CSS级关键字一样,它可以应用于任何CSS属性,包括全部的CSS缩写。如果该属性从其父级继承,则将属性重置为其继承的值,否则,将其重置为其初始值。换句话说,在第一种情况下,它的行为类似于Inherit关键字,在第二种情况下,其行为与初始关键字类似。

因此,根据您的示例:

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属性的跨浏览器兼容性时,我会建议谨慎……截止到今天。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.