2

I try to use CSS variables for width, heights and margin of a ::before element. It works all right for width and margin, but heights is 0.

Is there a way to resolve that? What is wrong?

html {
  --red_W: 80%;
  --red_H: calc(var(--red_W) / 4);
  --red_H_neg: calc(var(--red_H) * -1);
}

.bottomline {
  margin-top: var(--red_H);
  text-align: center;
  border-top: 10px solid green;
}
.inside::before{
  content: '';
  background-color: red;
  width: var(--red_W);
  height: var(--red_H); /*this does not seem to work*/
  margin: var(--red_H_neg) auto 0;
  display: block;
  position: relative;
}
<div class="bottomline">
  <div class="inside">
  </div>    
</div>

https://codepen.io/lorelorel/pen/wvqyLmy

TylerH
  • 20,799
  • 66
  • 75
  • 101
Lore
  • 21
  • 2
  • I don't think it would since its equating to 80%....80% of what? The parent would need a calculable height... and it doesn't have one. – Paulie_D Nov 05 '21 at 17:19
  • Why are you using `height` 2 times?? You are first assigning the height to 100px and then to var(--red_H). –  Nov 05 '21 at 17:26
  • @Avi Using twice as fallback. Added comment to make it clear. – Lore Nov 05 '21 at 17:35
  • @Paulie_D 80% of containing block, so window width in this case – Lore Nov 05 '21 at 17:36
  • Actually your variables are undefined, so width or its value dont matter – Tiko Nov 05 '21 at 17:38
  • no, it doesn't work that way. Variable doesn't store the calculation but only the "20%" so you end having height:20% which will fail because no height on parent – Temani Afif Nov 05 '21 at 19:50

1 Answers1

0

@Paulie_D was correct that you have to have a parent with a calculable height in order to use a percentage value for height. And since it is a pseudo element, the parent you would need to target is the .inside element. So to be explicit about how you can fix it you could do something like the following:

html {
  --red_W: 80%;
  --red_H: calc(var(--red_W) / 4);
  --red_H_neg: calc(var(--red_H) * -1);
}

.bottomline {
  margin-top: var(--red_H);
  text-align: center;
  border-top: 10px solid green;
}
.inside {
  height: 50px;
}
.inside::before{
  content: '';
  background-color: red;
  width: 80%;
  height: 100px;
  margin: -100px auto 0;
  width: var(--red_W);
  height: var(--red_H); /*this does not seem to work*/
  margin: var(--red_H_neg) auto 0;
  display: block;
  position: relative;
}
rofrol
  • 14,438
  • 7
  • 79
  • 77