2015-11-20 54 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屬性......這是今天的時候我會建議謹慎。

相關問題