Skip to content Skip to sidebar Skip to footer

Making Div Width Equal To The Longest Word/sentence Length Inside It

I want to make div width equal to content longest word/sentence length. Here is sample:
I_want_to_make_div_width_equal_to_this_word
It works fine wit

Solution 1:

New Edit from OP's comments :

The only way I can see to resolve this is using javascript, I made a uggly and probably overkilling snippet which does the work : It creates a clone of the node, set it as inline with white-space: nowrap and then add each word one at a time, compare the clone width with parent's width. If it's larger, then it assigns display: table-caption to the orginal div, else it adds the next word.

CSS

div {
    display: inline-block;
    background-color:pink;
    margin-bottom:5px;
}
.caption {
    display : table-caption;
}
.cloned {
    visibility : hidden;
    white-space : nowrap;
}

Javascript

varclone, el,w;

(cloneIt)();
functioncloneIt(){
    el = document.getElementById('3');
    clone = el.cloneNode(true);
    clone.className = "cloned";
    el.parentNode.appendChild(clone);
    w = clone.innerHTML.split(' ');
    wrapIt();
}
window.onresize = wrapIt;

functionwrapIt(){
    clone.innerHTML = w[0]; //minimum content is first wordfor(i=1; i<w.length; i++){
        clone.innerHTML += w[i]+' ';//add next wordif(i==w.length-1 && clone.offsetWidth <= el.parentNode.offsetWidth){
            //we're at the end and it's still smaller than parent width?
            el.style.width = clone.offsetWidth+ 1 + 'px';
            return;
            }
        if(clone.offsetWidth <= el.parentNode.offsetWidth){ 
            //add a new wordcontinue;
        }
        //Gone too far? remove last wordclone.innerHTML = clone.innerHTML.replace(w[i], '');
        el.style.width = clone.offsetWidth+ 1 + 'px';
        return;
     }
}

Here is Fiddle

Solution 2:

You must set a width for your div, or you can put your text inside a <p></p> tag and set the width for your paragraph on CSS.

Example:

#3 {
 width: 300px;
}

or, if you want something more semantic:

#3p {
  width: 300px;

}

Solution 3:

It is actually impossible to create linebreak without wraping the elements around something like a span or a div for example. So make the html like this:

<divid="1">I_want_to_make_div_width_equal_to_this_word</div><divid="2">I_want_to_make_div_width_equal_to_this_word
   <br/>and_anther_word_in_next_line
</div><divid="3"><span>I_want_to_make_div_width_equal_to_this_word</span><span>and_anther_word_in_next_line</span></div>

And the CSS like this:

divspan{
   display:block;
}

jsFiddle

Post a Comment for "Making Div Width Equal To The Longest Word/sentence Length Inside It"