2015-11-20 52 views
16

一个简单的例子:CSS中的初始值和未设置值有什么区别?

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; 
} 

是什么initialunset之间的区别?仅支持浏览器

CanIUse: CSS unset value

Developer Mozilla Web CSS initial

+1

根据你的链接:“如果没有继承财产*‘’*'unset'是一个CSS值是一样的‘继承’如果一个属性是继承或”初始 –

回答

15

移动我的评论一个答案

根据your link

unset是一个CSS值是一样的“继承“如果一个属性是继承的,或者是”初始“,如果一个道具erty是不能继承

下面是一个例子:

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>

+1

很好的例子,谢谢 – zloctb

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关键字是初始的组合和继承的关键字。与其他两个CSS范围的关键字一样,它可以应用于任何CSS属性,包括CSS速记all。如果该属性继承自其父项,则将该属性重置为其继承的值,否则将该属性重置为其初始值。换句话说,它的行为就像第一种情况下的继承关键字,并且像第二种情况下的初始关键字一样。

因此,根据你的例子:

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>

注意如何未设置属性只是重置元素的color财产。

总之

的想法是相当简单的,但在实践中与跨浏览器兼容处理两个CSS属性......这是今天的时候我会建议谨慎。

相关问题