DEV Community

Discussion on: An Innovative Idea for Holding State in CSS

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

Do you think it's possibe to have:

--variabe: true;
--variabe: false;
Enter fullscreen mode Exit fullscreen mode

Somehow to toggle between two values using mutipe css variables and your technique?

I would be nice for libraries that use configuration to style the output.

So far for my jQuery Terminal I've used CSS boolean trick from artice: Conditions for CSS Variables. But it ony works with numbers. At least this is how I us it. I have --glow: 1 to enabe glow on text (using text shadow).

Collapse
 
janeori profile image
Jane Ori • Edited
.test {
--true: ;
--false: initial;
--variable: var(--false);

--red-if-true: var(--variable) red;
background: var(--red-if-true, blue);
}
.test:hover {
  --variable: var(--true);
}
Enter fullscreen mode Exit fullscreen mode

background of .test is blue unless you hover, it's red.

There is one major downside to this though, and it's complicated.
If you have .test nested inside another .test element and --red-if-true computes to initial (false) on the child, it will inherit first instead of using the fallback immediately in a few browsers.
The spec used to say inheriting was correct but they fixed it so the fallback will be used instead of inheriting as part of the Houdini spec when I pointed out the problem. Chrome will use fallback for all but a few versions from about a year ago. Firefox used to use fallback but they won't again until they implement Houdini. Safari inherits.
It's extremely unfortunate.

The fix is to use an intermediate reset layer that explicitly sets the computed variable to initial so when inheriting behavior is present, it inherits initial and the fallback is used even if the outer-most .test is truthy:

<span class="test">
  <span style="--red-if-true: initial;">
    <span class="test"></span>
  </span>
</span>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

Thanks for explanation. I've noticed that this doesn't work in Chrome:

html:hover {
  --enable: paused;
  animation-play-state: var(--enable) running;
}
Enter fullscreen mode Exit fullscreen mode

Inside this demo: codepen.io/propjockey/pen/b01b6646...

Does it only work with token initial and space?

Thread Thread
 
janeori profile image
Jane Ori

Yes, the space toggle is only initial and space. The tl;dr on space toggles in the article should help explain what's happening. LMK if you want more clarity on something, happy to help!

Thread Thread
 
jcubic profile image
Jakub T. Jankiewicz • Edited

So:

--var: initial;
Enter fullscreen mode Exit fullscreen mode

Just reset CSS variable to initial value which is no value at all. Am I right? If so I would write this in TL;DR section. I wonder how it would behave if you register the CSS variable in JavaScript with initial value.