J'ai écrit un plugin jQuery qui fait cela. Ce n'est pas ce qu'il y a de plus stable, mais pour des solutions plus modestes, je pense que cela fonctionnera :
Voyez-le en action : (au JS Bin )
!function($){
$.fn.calcMaxWidth = function(maxWidth) {
maxWidth = !maxWidth || isNaN(maxWidth) ? 200 : maxWidth;
return this.each(function() {
var i,y,
tempObject,
thisObject = this,
$this = $(this),
$contents = $this.contents(),
tempContents = [],
tempMaxWidth = 0;
$contents.each(function() {
tempContents.push(this);
});
$this.empty();
while(tempContents.length) {
tempObject = tempContents.shift();
if ( tempObject.nodeName == "#text" ) {
tempObject = $(tempObject).text().split(" ");
for ( i = tempObject.length; i>0; i-- ) {
tempContents.unshift(tempObject[i-1] + " ");
}
continue;
}
$this.append( tempObject );
if ( $this.width() < maxWidth && $this.width() > tempMaxWidth )
tempMaxWidth = $this.width();
else {
$this.empty();
}
}
$this
.css("width", tempMaxWidth || maxWidth)
.append($contents);
});
}
}(jQuery);
Et l'usage :
$("div.t").calcMaxWidth(200);
Mon DOM pour l'exemple :
<div class="l t">
This text is so long that we have to break it, The max width is <code>200px</code>.
<span>a span tag</span>
<a href="http://goggle.com">A link...</a>
<br />
Using jQuery
</div>
<img src="" />
<div style="clear:both"></div>
<div class="l">
This text is so long that we have to break it, The max width is <code>200px</code>.
<span>a span tag</span>
<a href="http://goggle.com">A link...</a>
<br />
Using CSS
</div>
<img src="" />
Et le style :
div.l {
float:left;
background:#fda;
max-width:200px;
overflow:hidden;
}
img {
overflow:hidden;
width:100px;
height:100px;
}
...
Andreas