Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Variables - Swapping values?

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?

like image 757
Ariel Abreu Avatar asked May 28 '18 14:05

Ariel Abreu


People also ask

Can CSS variables be changed?

CSS variables have access to the DOM, which means that you can change them with JavaScript.

How do I create a custom variable in CSS?

To declare a variable in CSS, come up with a name for the variable, then append two hyphens (–) as the prefix. The element here refers to any valid HTML element that has access to this CSS file. The variable name is bg-color , and two hyphens are appended.


1 Answers

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>
like image 93
Temani Afif Avatar answered Sep 28 '22 06:09

Temani Afif