Florian Müller
Florian Müller

Reputation: 7785

Find out the effective width of element and resize text in it

I'd like to find out the width of a TD which has defined style='width: 200px;, but the text makes it longer (no break). I want to find out the effective width and, as long it is bigger than 200px, shrink the text size in it for about 2px each time.

Is this possible at all?

Upvotes: 2

Views: 612

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382274

This can be done in javascript but it's a little complex.

Here's the complete working example : http://jsfiddle.net/dystroy/kdrrA/

The HTML :

<table><tr><td id=txtcell nowrap><span id=txt>My long text is long. My long text.</span></td></tr></table>
<br>Font Size : <span id=mes></span>​

The CSS :

#txtcell{ max-width:200px;}

The javascript :

var fontSize = 20; 
var reduce = function() { 
    while ($('#txt').width() > 200) { 
        fontSize -= 1; 
        $('#txt').css('font-size', fontSize); 
    }
    $('#mes').html(fontSize); // this line is only for demonstration, remove it in "production"
}; 
reduce();

Note that I had to add a span in the cell because TD width computation by jquery doesn't work very well.

Upvotes: 3

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

You need JavaScript to make it. But if you wish to make it using CSS alone, you can use CSS expressions with expression.

td {width: expression(this.style.width);}

Hope it helps! :)

Upvotes: 0

Related Questions