CSS variable not working with height of ::before

Viewed 482

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

1 Answers

@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;
}
Related