int3
int3

Reputation: 13201

Is it possible to resize text to fit a fixed size div?

This seems like a pretty natural use case to me, though I haven't been able to find anything on it:

Say I have a fixed-width div that is dynamically populated with some number. What's the best way to ensure that numbers with more digits take smaller font sizes such that they fit nicely into that fixed width? Is there some CSS property for this, or do I have to resort to Javascript hackage?

Upvotes: 5

Views: 4211

Answers (2)

kaore
kaore

Reputation: 1368

Css does not do this, but you might want to give these scripts a go: http://www.zachleat.com/web/fittext-and-bigtext/

Upvotes: 3

timmfin
timmfin

Reputation: 2055

There is no CSS property which automatically adjusts font-sizes based on a fixed container. You will have to resort to javascript.

You could put each number in a span, and loop over each span checking its width. If the width is greater than the fixed width, bump the font-size down and then check the width again. Keep on lowering the font-size until the span's width is less than the fixed width.

To prevent flickering, you should perform this loop checking while the fixed div is visible, but placed off page (such as "position: absolute; left: -5000px;")

Upvotes: 3

Related Questions