Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 236
int3 Avatar asked Mar 23 '10 02:03

int3


People also ask

How do I resize a content to fit in a div?

Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.

How do I give a div a fixed size?

Use a the clearer div to force the main section to extend its height when the content div expands. At this point, you have a fluid-width layout. To convert it to a fixed-width layout, simply add a fixed with to the #wrapper and set the margins to auto.

How do I resize text in CSS?

To change the size of your text with inline CSS, you have to do it with the style attribute. You type in the font-size property, and then assign it a value.


1 Answers

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

like image 159
timmfin Avatar answered Oct 18 '22 00:10

timmfin