CSS: set the font size so that the text occupies the entire container

Possible duplicate:
change the font size to fit in a div (in one line)

For a small application for creating flash cards, I need to set the correct font size so that the text fills the entire available width of the container with a fixed size; like text in four boxes in this image: two flashcards with text filling all available card area

A solution using PHP GD was provided to this question . Is there a client problem with css or javascript for this problem?

+7
source share
3 answers

this is not brute force;)

HTML:

<span id="txt">Lorem</span> <div id="card"></div> 

CSS

 #card { width: 150px; height: 50px; border: 1px solid black } #txt { display: none } 

JS (using jQuery):

 var size_w = (150/$('#txt').width() - 0.05); var size_h = (50/$('#txt').height() - 0.05); var size = size_w>size_h?size_h:size_w; $('#card').css('font-size', size + 'em'); $('#card').text($('#txt').text()); 

fiddle here: http://jsfiddle.net/cwfDr/

Ok, now it covers both height and width .;)

+3
source

I wrote this tiny tiny plugin to fit the browser window.

  (function($){ $.fn.extend({ sizeFont: function() { return this.each(function() { $obj = $(this); $obj.css({fontSize:($(window).width()/$obj.width())+'em'}); }); } }); })(jQuery); 

I'm sure you can change this to suit your needs by switching $(window) to whatever you want. Here it is live:

http://cullywright.com/

+2
source

I studied these years ago, and we decided that the only logical way to do this, which did not cause madness, was to use images instead of text for numbers, and then calculate the size of the images needed based on the width of the container (we also had text). In addition, we used a fixed-width font selected for numbers / text.

Another alternative is replacing flash text, which gives you more control: http://www.mikeindustries.com/blog/archive/2004/08/sifr

There may be other methods developed over the past few years, and maybe CSS3 may help (although it may not be widely supported if that is the case), but the image method has given us the best bang for the buck.

+1
source

All Articles