初期値と未設定値の違いは何ですか?


回答:


111

あなたのリンクによると:

unset プロパティが継承されている場合は「inherit」、プロパティが継承されていない場合は「initial」と同じ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要素のプロパティを。

UNSET

未設定のCSSキーワードは、初期キーワードと継承キーワードの組み合わせです。これらの他の2つのCSS全体のキーワードと同様に、CSSの省略形allを含む任意のCSSプロパティに適用できます。このキーワードは、プロパティを親から継承する場合は継承値にリセットし、継承しない場合は初期値にリセットします。つまり、最初のケースではinheritキーワードのように動作し、2番目のケースでは最初のキーワードのように動作します。

したがって、あなたの例によると:

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プロパティのブラウザー間の互換性を扱うときは注意が必要です...それは今日の時点です。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.