Search code examples
htmlcss

set the font size of a child element relative to the height of its parent box when the parent box doesn't have a specified font size


I need to dynamically set the font size of the <span> element relative to the 10% height of the div.

HTML:

<div>
  <span>Example text</span>
</div>

CSS:

div {
  height: 20vh;
  width: 100vh;
  background-color: #f0f0f0;
  position: relative;
}

I tried using vh, vmin, rem, em, % units with no luck. Is there a way to achieve this with pure CSS? Without relying on JavaScript?


Solution

  • Use Container Queries/Units

    Container queries enable you to apply styles to an element based on the size of the element's container. If, for example, a container has less space available in the surrounding context, you can hide certain elements or use smaller fonts.

    The container query length units are:

    • cqw: 1% of a query container's width
    • cqh: 1% of a query container's height
    • cqi: 1% of a query container's inline size
    • cqb: 1% of a query container's block size
    • cqmin: The smaller value of either cqi or cqb
    • cqmax: The larger value of either cqi or cqb

    div {
      height: 30vh;
      width: 100vh;
      background-color: #f0f0f0;
      container-type: size;
      margin-bottom: 1em;
    }
    
    span {
      font-size: 10cqh;
    }
    
    .big {
      font-size: 20cqh;
    }
    <div>
      <span>Example text</span>
    </div>
    <div>
      <span class="big">Example text</span>
    </div>