CSS Variables - Swapping values?

痞子三分冷 提交于 2019-11-30 17:50:01

问题


I have a very simple problem with CSS variables. I would like to swap two CSS variables, basically the CSS equivalent of [a, b] = [b, a] in ES6. Here's a simple example:

<p>White background</p>
<button>Black background</button>
<div>
  <p>Black background</p>
  <button>White background</button>
</div>
:root {
  --primary-color: #fff;
  --secondary-color: #000;
}

body {
  background-color: var(--primary-color);
}

button {
  background-color: var(--secondary-color);
}

div {
  /* i'd like to do the following: */
  --primary-color: var(--secondary-color);
  --secondary-color: var(--primary-color);

  /* so here, `--primary-color` would be `--secondary-color` from `:root`
   * and any children have these colors swapped as well
   */
  background-color: var(--primary-color);
}

However, this fails because CSS var()s are live bindings. Am I missing something here? Or is this the way the spec currently works?


回答1:


You are creating a cyclic dependence because you are defining each property using the other one and this won't work. Instead you may try something like this by introducing more variables:

:root {
  --p:#fff;
  --s:#000;
  --primary-color: var(--p);
  --secondary-color: var(--s);
}

body {
  background-color: var(--primary-color);
}

button {
  background-color: var(--secondary-color);
}

div {
  /* i'd like to do the following: */
  --primary-color: var(--s);
  --secondary-color: var(--p);
  
  background-color: var(--primary-color);
}
<p>White background</p>
<button>Black background</button>
<div>
  <p>Black background</p>
  <button>White background</button>
</div>


来源:https://stackoverflow.com/questions/50568291/css-variables-swapping-values

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