CSS variables defaults: set if not already set

白昼怎懂夜的黑 提交于 2020-07-16 04:14:09

问题


My Web Component uses CSS variables.

These variables need default values.

They are used in many files, so I want to provide the defaults once, and only once.

This first attempt makes the text black. Why?

What is the correct way to provide the defaults once?

.a {
  --my-variable: red;
}

.b {
  --my-variable: var(--my-variable, blue);
}
<div class="a">
  <div class="b">
    <span style="color: var(--my-variable);">text</span>
  </div>
</div>

回答1:


This first attempt makes the text black. Why?

Because this --my-variable: var(--my-variable, blue); is invalid as you are trying to express the same variable with itself which is not allowed so the browser will simply ignore it. Then later when using color: var(--my-variable); the color will fallback to the initial value which is black.

The correct way is to simply define the variable on an upper level and it will get inherited by all the element (like the solution provided by @kornieff)


From the specification:

Custom properties are left almost entirely unevaluated, except that they allow and evaluate the var() function in their value. This can create cyclic dependencies where a custom property uses a var() referring to itself, or two or more custom properties each attempt to refer to each other.

For each element, create a directed dependency graph, containing nodes for each custom property. If the value of a custom property prop contains a var() function referring to the property var (including in the fallback argument of var()), add an edge between prop and the var. Edges are possible from a custom property to itself. If there is a cycle in the dependency graph, all the custom properties in the cycle must compute to their initial value (which is a guaranteed-invalid value).




回答2:


Declare default values in :root, then override in selectors.

:root {
  --primary-color: red;
}

* {
  color: var(--primary-color);
  border: 1px solid var(--primary-color);
  padding: 0.25rem;
  margin: 0;
}

div {
  --primary-color: green;
}

p {
  --primary-color: blue;
}
<div>HI!</div>
&hellip;
<p>Bye!</p>


来源:https://stackoverflow.com/questions/59015022/css-variables-defaults-set-if-not-already-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!