Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shrink DIV to text that's wrapped to its max-width?

Tags:

Shrink wrapping a div to some text is pretty straightforward. But if the text wraps to a second line (or more) due to a max-width (as an example) then the size of the DIV does not shrink to the newly wrapped text. It is still expanded to the break point (the max-width value in this case), causing a fair amount of margin on the right side of the DIV. This is problematic when wanting to center this DIV so that the wrapped text appears centered. It will not because the DIV does not shrink to multiple lines of text that wrap. One solution is to use justified text, but that isn't always practical and the results can be hideous with large gaps between words.

I understand there's no solution to shrink the DIV to wrapped text in pure CSS. So my question is, how would one achieve this with Javascript?

This jsfiddle illustrates it: jsfiddle. The two words just barely wrap due to the max-width, yet the DIV does not then shrink to the newly wrapped text, leaving a nasty right-hand margin. I'd like to eliminate this and have the DIV resize to the wrapped text presumably using Javascript (since I don't believe a solution exists in pure CSS).

.shrunken {text-align: left; display: inline-block; font-size: 24px; background-color: #ddd; max-width: 130px;}  <div class="shrunken">Shrink Shrink</div> 
like image 287
onlinespending Avatar asked Jan 30 '13 03:01

onlinespending


People also ask

How do I change the width of a div in text?

Using inline-block property: Use display: inline-block property to set a div size according to its content.

How do I force wrap text in a div?

You can try specifying a width for the div, whether it be in pixels, percentages or ems, and at that point the div will remain that width and the text will wrap automatically then within the div.

How do I wrap text in a specific width in CSS?

AS long as you've set the width of the element, just take the whitespace:no-wrap off, and it will wrap the text exactly to the width of the element.

How do I wrap text in next line in CSS?

FYI: You can use either the 'normal' or 'break-word' value with the word-wrap property. Normal means the text will extend the boundaries of the box. Break-word means the text will wrap to next line. word-break: break-word; worked for me.


1 Answers

It's not the prettiest solution but it should do the trick. The logic is to count the length of each word and use that to work out what the longest line is that will fit before being forced to wrap; then apply that width to the div. Fiddle here: http://jsfiddle.net/uS6cf/50/

Sample html...

<div class="wrapper">     <div class="shrunken">testing testing</div> </div>  <div class="wrapper">     <div class="shrunken fixed">testing testing</div> </div>  <div class="wrapper">     <div class="shrunken">testing</div> </div>  <div class="wrapper">     <div class="shrunken fixed">testing</div> </div>  <div class="wrapper">     <div class="shrunken" >testing 123 testing </div> </div>  <div class="wrapper">     <div class="shrunken fixed" >testing 123 testing </div> </div> 

And the javacript (relying on jQuery)

$.fn.fixWidth = function () {     $(this).each(function () {         var el = $(this);         // This function gets the length of some text         // by adding a span to the container then getting it's length.         var getLength = function (txt) {             var span = new $("<span />");             if (txt == ' ')                 span.html('&nbsp;');             else                 span.text(txt);             el.append(span);             var len = span.width();             span.remove();             return len;         };         var words = el.text().split(' ');         var lengthOfSpace = getLength(' ');         var lengthOfLine = 0;         var maxElementWidth = el.width();         var maxLineLengthSoFar = 0;         for (var i = 0; i < words.length; i++) {             // Duplicate spaces will create empty entries.             if (words[i] == '')                 continue;             // Get the length of the current word             var curWord = getLength(words[i]);             // Determine if adding this word to the current line will make it break             if ((lengthOfLine + (i == 0 ? 0 : lengthOfSpace) + curWord) > maxElementWidth) {                 // If it will, see if the line we've built is the longest so far                 if (lengthOfLine > maxLineLengthSoFar) {                     maxLineLengthSoFar = lengthOfLine;                     lengthOfLine = 0;                 }             }             else // No break yet, keep building the line                 lengthOfLine += (i == 0 ? 0 : lengthOfSpace) + curWord;         }         // If there are no line breaks maxLineLengthSoFar will be 0 still.          // In this case we don't actually need to set the width as the container          // will already be as small as possible.         if (maxLineLengthSoFar != 0)             el.css({ width: maxLineLengthSoFar + "px" });     }); };  $(function () {     $(".fixed").fixWidth(); }); 
like image 163
SynXsiS Avatar answered Nov 10 '22 01:11

SynXsiS