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?

Answers:

Answer

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.

Answer

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! :)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.