Skip to content

CSS Auto Font Scaling

The new CSS Container Queries are actually much more useful than for just switching between different discrete CSS styles. They can actually be easily repurposed for other things such as dynamic font sizing to stop text from clipping off the screen

hi
because
pneumonoultramicroscopicsilicovolcanoconiosis

css
.scaler {
    font-size: 14pt; /*fallback*/
    container-type: inline-size;
    --char-aspec-ratio: 1.8;
}

.auto-scaling-font {
    font-size: min(
        60px,
        calc(100cqw / var(--chars) * var(--char-aspec-ratio))
    );
}
html
<div class="boundary scaler">
    <div class="auto-scaling-font" style="--chars: 2">
        hi
    </div>
    <div class="auto-scaling-font" style="--chars: 7">
        because
    </div>
    <div class="auto-scaling-font" style="--chars: 45">
        pneumonoultramicroscopicsilicovolcanoconiosis
    </div>
</div>