2

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Florian Müller
  • 7,448
  • 25
  • 78
  • 120

2 Answers2

3

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I've edited your JS a bit, because the Interval does have too much time so the user sees the interaction. With this, it works very well: var fontSize = 20; var reduce = function() { while ($('#txt').width() > 200) { fontSize -= 1; $('#txt').css('font-size', fontSize); } $('#mes').html(fontSize); }; reduce(); – Florian Müller Jun 08 '12 at 08:06
  • 1
    OK. You may edit directly my answer if you think this may be useful for other people. – Denys Séguret Jun 08 '12 at 08:08
  • This answer is a perfect candidate for improvement by binary search. – par Jun 16 '14 at 20:06
0

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

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • CSS expressions are only compatible with Internet Explorer and even Microsoft dropped them long time ago. http://stackoverflow.com/questions/3810478/which-browsers-still-support-css-expressions – Denys Séguret Jun 08 '12 at 08:02