Everettss Everettss - 4 months ago 12x
HTML Question

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:

<div id="1">I_want_to_make_div_width_equal_to_this_word</div>

It works fine with this css code:

div {display: inline-block;}

It also works in this example:

<div id="2"> I_want_to_make_div_width_equal_to_this_word <br/>
and_anther_word_in_next_line </div>

Div with id="2" has a width of the longest word.

But my problem is with this example. When content window is too small to contain both words in one line, div have width of 100% window size:

<div id="3"> I_want_to_make_div_width_equal_to_this_word
and_anther_word_in_next_line </div>

Is it possible for the div with id=3 to behave like id=2 but without
<br />

Examples I just described: http://jsfiddle.net/2vffqrwy/ (make width of window that break words in third div into two separate lines).

The perfect solution is when div id=3 display both words in one line when window is big enough and behaves like div id=2 when window is to small to contain both words in one line.


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.


div {
    display: inline-block;
.caption {
    display : table-caption;
.cloned {
    visibility : hidden;
    white-space : nowrap;


 var clone, el,w;

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

function wrapIt(){
    clone.innerHTML = w[0]; //minimum content is first word
    for(i=1; i<w.length; i++){
        clone.innerHTML += w[i]+' ';//add next word
        if(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';
        if(clone.offsetWidth <= el.parentNode.offsetWidth){ 
            //add a new word
        //Gone too far? remove last word
        clone.innerHTML = clone.innerHTML.replace(w[i], '');
        el.style.width = clone.offsetWidth+ 1 + 'px';

Here is Fiddle