views:

253

answers:

1

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?

+2  A: 

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;")

timmfin