Edge to Edge Text

I kid you not: Roman Komarov’s Fit-to-Width Text is one of my favorite CSS tricks I’ve ever seen. It’s, uh, quite a treat (that’s all you’re going to get here on Halloween, sorry). It’s just so strange. The end result is that you can size a line of text such that it hits the left and right edge of a container perfectly.

This is a very legitimate need that people have been solving for ages. If the container is a fixed size, you can solve it by setting ultra specific font sizes. But more likely these days, containers are of unknown widths, leaving us to JavaScript for figuring out how big of text we can fit in there. FitText was a seminal example. These days, we can also do it with container units, but it’s still extremely fiddly. Wouldn’t it be nice to be like font-size: make-it-fit;?

Roman’s trick is as close to that as can be. Check out his post for all the details, but the core concept is that it uses scroll-driven animations. The text gets set pretty big by default, then a scroll-driven animation is set on it which runs scales the text down essentially until animation-range: entry-crossing; is fulfilled then stops. Here’s an example with just one word (free free to resize and see):

The absolute core of the idea is:

@supports (animation-range: entry-crossing) {
  .fit-to-width {
    font-size: 12rem; /* max-font-size */
    overflow: hidden;

    & > * {
      inline-size: max-content;
      transform-origin: 0 0;
      animation: apply-text-ratio linear;
      animation-timeline: view(inline);
      animation-range: entry-crossing;
      display: block;
    }
  }
}

@keyframes apply-text-ratio {
  from {
    scale: 0;
    margin-block-end: -1lh;
  }
}Code language: CSS (css)

Like Roman’s original demo, it works great on multiple lines, actually showing off the power of the technique much better. The design of “multiple lines sized to fit exactly on a line” made me think of those “In this house we believe…” signs, so I made my own:

That demo has contenteditable on it so you can mess with the letters and see it work.

If, like me, you have a hard time wrapping your mind around the trick, note that you can inspect the animations in Chrome DevTools and see how each span has a different length of animation:

I think the longer the animation the more the text scales down toward zero. Phew — I told you it was weird.

Wanna be a better web typographer?

3 responses to “Edge to Edge Text”

  1. David White says:

    This is pretty clever, even if it only works in Chrome and Edge right now.

Leave a Reply

Your email address will not be published. Required fields are marked *

Did you know?

Frontend Masters Donates to open source projects. $363,806 contributed to date.