1

I have a flex box and I also want it to be hidden (display: none !important) only if a variable is set.

.d-flex {
  display: flex; /*Set by Bootstrap library*/
}

.my-item {
  display: var(--display); /*Should only apply if --display is set*/
}

.container.hide-items {
  --display: none !important;
}
<div class="container">
  <div class="d-flex my-item">Flexbox 1 (not hidden)</div>
  <div class="d-flex my-item">Flexbox 2 (not hidden)</div>
</div>

<div class="container hide-items">
  <div class="d-flex my-item">Flexbox 1 (hidden)</div>
  <div class="d-flex my-item">Flexbox 2 (hidden)</div>
</div>

The above code only works when hide-items exists but when --display is undefined, the browser just falls back into (probably) inline. I know var() accepts fallback values but I do not know how to set it so the element stays to whatever it was set before (in this case flex), I have tried unset or initial but they don't get their flex value back. Is this possible?

enter image description here

Luke Vo
  • 17,859
  • 21
  • 105
  • 181
  • Once you drop the CSS `property: value`, you redefine it no matter was it defined in the other selector or not (if the `value` is valid and your current selector has greater specificity). Still you can use the `var(--variable-name, default-value)` syntax to set the default value if the `--variable-name` was not defined. In your case that could be: `display: var(--display, flex);` or `display: var(--display, inherit);`. The latter will not take the value from another definition, but will inherit parent element's `display` value. – Jared Jun 27 '23 at 13:04

1 Answers1

0

You will I think have to 'repeat' the Bootstrap flex setting.

This snippet sets the --display variable to flex for .container .d-flex.my-item elements and then sets it to none for .container.hide-items .d-flex.my-item

.d-flex {
  display: flex; /*Set by Bootstrap library*/
}

.container .d-flex.my-item {
  display: var(--display);
}
.container  .d-flex.my-item {
  --display: flex;
}
.container.hide-items .d-flex.my-item {
  --display: none !important;
}
<div class="container">
  <div class="d-flex my-item">Flexbox 1 (not hidden)</div>
  <div class="d-flex my-item">Flexbox 2 (not hidden)</div>
</div>

<div class="container hide-items">
  <div class="d-flex my-item">Flexbox 1 (hidden)</div>
  <div class="d-flex my-item">Flexbox 2 (hidden)</div>
</div>
A Haworth
  • 30,908
  • 4
  • 11
  • 14