1

I'm not sure I understand CSS variables. In the example below, why does the div not appear when the button is hovered over?

:root {
  --op: hidden;  
}
button:hover {
  background-color: yellow;
  --op: visible;
}
div {
  visibility: var(--op);
  width: 100px;
  height: 100px;
  background-color: red;
}
<button>Hover</button><div></div>
TorNato
  • 305
  • 2
  • 12

3 Answers3

3

You're not actually targeting the hidden div. Try using the adjacent selector.

The adjacent sibling combinator (+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element.

:root {
  --op: hidden;  
}
button:hover {
  background-color: yellow;
}

button:hover + div {
  --op: visible;
}

div {
  visibility: var(--op);
  width: 100px;
  height: 100px;
  background-color: red;
}
<button>Hover</button><div></div>
Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
  • 1
    @TorNato the answer to [this question](https://stackoverflow.com/questions/54958699/reassign-css-variable-to-when-original-variable-changes) explains it. Your `div` got drawn once at the beginning and got its visibility set to hidden. Changing the variable afterwards doesn't affect the div anymore. – Tad Wohlrapp May 02 '20 at 02:05
  • 1
    Okay, I get it :). Thank you to both of you! – TorNato May 02 '20 at 02:08
-1

That's not working because you are setting the variable only for the button, so you are not overriding the global variable.

What you can do is overriding its value with javascript on the button hover. This will exclude any css sibling limitation to work:

function changeGlobalVariable(visible) {
  document.documentElement.style.setProperty('--op', visible ? 'visible' : 'hidden');
}
:root {
  --op: hidden;  
}
button:hover {
  background-color: yellow;
}
div {
  visibility: var(--op);
  width: 100px;
  height: 100px;
  background-color: red;
}
<button
  onmouseover="changeGlobalVariable(true)"
  onmouseout="changeGlobalVariable(false)">Hover</button><div></div>
Freeky
  • 810
  • 4
  • 14
-3

Try setting up class/id for div like

#idname {
  visibility: var(--op);
  width: 100px;
  height: 100px;
  background-color: red;
}

On view use

<div id="idname"></div>