Closed6

CSS のスペーストグルってなんだ?

小原一哉小原一哉

https://developer.mozilla.org/ja/docs/Web/CSS/Using_CSS_custom_properties

MDN に載ってる CSS カスタムプロパティの基本的な説明。
(これまで CSS Variables と読んでいたけどカスタムプロパティか変数と言ったほうがいいかも)

var() 関数を使用して、指定された変数が定義されていない場合の代替値を複数定義することができます。

まあこれはいつも使っているやつなので馴染みある。

メモ: 代替値の構文は、カスタムプロパティの場合のように、カンマを使用することができます。例えば、 var(--foo, red, blue) は red, blue という代替値を定義します。最初のカンマから関数の終わりまでが代替値とみなされます。

本筋ではないけどだけどこれは知らんかった…。

小原一哉小原一哉

https://drafts.csswg.org/css-variables/#using-variables

To substitute a var() in a property's value:

  1. If the custom property named by the first argument to the var() function is animation-tainted, and the var() function is being used in a property that is not animatable, treat the custom property as having its initial value for the rest of this algorithm.
  2. If the value of the custom property named by the first argument to the var() function is anything but the initial value, replace the var() function by the value of the corresponding custom property.
  3. Otherwise, if the var() function has a fallback value as its second argument, replace the var() function by the fallback value. If there are any var() references in the fallback, substitute them as well.
  4. Otherwise, the property containing the var() function is invalid at computed-value time.

NOTE: Other things can also make a property invalid at computed-value time.

カスタムプロパティが未定義で var() のフォールバック値もない場合、1,2,3 に当てはまらず 4 になるのでプロパティが計算値の時点で無効になるらしい。

つまり未定義のカスタムプロパティを使おうと

.a {
  background: var(--undef-var);
}

と書くと、何も指定していないのと一緒になる。

小原一哉小原一哉

改めてスペーストグルのテクニックを読んでみると

  --toggler: ;
  --red-if-toggler: var(--toggler) red;
  background: var(--red-if-toggler, green); /* will be red! */

--toggle が定義されているので、--red-if-togglerred と定義されることになり background: red となり、一方で

  --toggler: initial;
  --red-if-toggler: var(--toggler) red;
  background: var(--red-if-toggler, green); /* will be green! */

--toggleinitial = 定義されていないので、--red-if-toggler というプロパティは無効 → 定義されていないことになり、background: green というフォールバック値になる。

わかった。

このスクラップは20日前にクローズされました