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?



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

Here's the complete working example :

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"

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


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(;}

Hope it helps! :)


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.