CSS Unit relative of parent elements height

Viewed 25

Is there any way in pure CSS to achieve having any property able to be a percentage of it's parent element height/width?

The below snippet I've set #b font-size to 20vh, however the goal is to have the font-size of #b always stay as half of the parent elements height as the container will be resizeable. Something like font-size: 50ph for parent height.

If not I will resort to using the ResizeObserver

#a {
  height: 40vh;
  display: flex;
  background-color: coral;
  justify-content: center;
  align-items: center;
}

#b {
  font-size: 20vh;
}
<div id="a">
  <div id="b">Text</div>
</div>

1 Answers

I was looking for a solution that set the font-size of the container depending on its width, then fix set the font-size of the content at 50% but it overflows, I tryed few values and it seems to always be 43.5% for some reason.

:root{
  --container-height: 50px;
}
.second.container{
  --container-height: 100px;
}
.third.container{
  --container-height: 300px;
}
.container{
  width:300px;
  height:var(--container-height);
  background-color:orange;
  font-size:var(--container-height);
}
.content{
  font-size:43.5%;
}
<div class="container">
  <div class="content">
    <div>Text</div>
    <div>Text</div>
  </div>
</div>
<br>
<div class="second container">
  <div class="content">
    <div>Text</div>
    <div>Text</div>
  </div>
</div>
<br>
<div class="third container">
  <div class="content">
    <div>Text</div>
    <div>Text</div>
  </div>
</div>

Related