Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Set font to a size so the text would occupy whole container [duplicate]

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?

like image 890
Majid Fouladpour Avatar asked Jan 30 '11 11:01

Majid Fouladpour


People also ask

How do I resize a font 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.

Which is used for font size of text in the CSS property sets?

The font-size CSS property sets the size of the font. Changing the font size also updates the sizes of the font size-relative <length> units, such as em , ex , and so forth.

How do I make text full width in CSS?

Just had to add text-justify: inter-character; to my styles, to have all chars across the full container width.


2 Answers

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

like image 89
marines Avatar answered Sep 21 '22 18:09

marines


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/

like image 24
Oscar Godson Avatar answered Sep 21 '22 18:09

Oscar Godson