CSS变量-交换值? [英] CSS Variables - Swapping values?

查看:80
本文介绍了CSS变量-交换值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的CSS变量问题.我想交换两个CSS变量,基本上是ES6中[a, b] = [b, a]的CSS等效项.这是一个简单的示例:

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);
}

但是,这失败了,因为CSS var()是实时绑定.我在这里想念什么吗?还是这是规范当前的工作方式?

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

推荐答案

您正在创建循环依赖项,因为您正在使用另一个属性来定义每个属性,因此这是行不通的.相反,您可以通过引入更多变量来尝试类似的操作:

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>

这篇关于CSS变量-交换值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆