Reputation: 2018
I have a styling issue in my webapp. I have a div with an adjacent image.
________________________
|_________div__________| [image]
I am facing a problem with the word wrap. Once the text inside becomes longer than the text. It wraps around. but since word wrapping streached the div to its max size before wrapping there is a bit of white space between the text and the image.
____________________
| This is stack |[image]
|_overflow___________|
now this behavior is not favorable. How would i get the Div to take up ONLY as much space as the text.
such as
______________
| This is stack|[image]
|_overflow_____|
Upvotes: 2
Views: 575
Reputation: 47099
I wrote a jQuery plugin that does this. It's not the most stabile thing but for smaller solutions i think it will work:
See it in action: (at 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);
And the usage:
$("div.t").calcMaxWidth(200);
My DOM for the example:
<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="" />
And the style:
div.l {
float:left;
background:#fda;
max-width:200px;
overflow:hidden;
}
img {
overflow:hidden;
width:100px;
height:100px;
}
...
Andreas
Upvotes: 1
Reputation: 25081
Try removing any declared widths for the div (or set it to width: auto
).
Upvotes: 2