7

Possible Duplicate:
resize font to fit in a div (on one line)

For a small flashcard maker app I need to set the correct font size so text would fill all the available width of a fixed-size container; like the text in the four boxes in this picture: two flashcards with text filling all available card area

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

Community
  • 1
  • 1
Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127

3 Answers3

3

it's 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/

All right, now it covers both height and width. ;)

marines
  • 2,693
  • 1
  • 16
  • 16
2

I wrote this tiny, tiny plugin to do it 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 modify this to fit your needs by switching $(window) to whatever you want. Here is it live:

http://cullywright.com/

Oscar Godson
  • 31,662
  • 41
  • 121
  • 201
1

I had looked into this years ago, and we decided the only logical way of doing it that didn't induce insanity was using images instead of text for the numbers, and then calculating the size of the images needed based on the width of the container (we also had text). Also, we used a fixed width font selected for the numbers/text.

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

There may be other techniques that have developed over the last few years, and maybe CSS3 could help (although it may not be broadly supported if it does), but the image technique gave us the best bang for the buck.

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • +1 - sIFR IS a true rescuer. Thanks so much. – Majid Fouladpour Jan 30 '11 at 18:43
  • No problem. Like I said, each method has it's own drawbacks, but we decided the image replacement method was the least problematic and most direct answer with the least amount of drawbacks. Having said that, sIFR is definitely a good way to go, especially since you can control the font itself from the server. – Jared Farrish Jan 30 '11 at 19:27