JSFiddle - React, Tailwind, and code Playground
HTML
<div id="1">I_want_to_make_div_width_equal_to_this_word</div>
<div id="2">I_want_to_make_div_width_equal_to_this_word
<br/>and_anther_word_in_next_line</div>
<div id="3">I_want_to_make_div_width_equal_to_this_word and_anther_word_in_next_line nice_but_what_with_third_word? and with another one? and again, and again</div>
CSS
div {
display: inline-block;
background-color:pink;
margin-bottom:5px;
}
.caption {
display : table-caption;
}
.cloned {
visibility : hidden;
white-space : nowrap;
}
JavaScript
var clone, el,w;
(cloneIt)();
function cloneIt(){
el = document.getElementById('3');
clone = el.cloneNode(true);
clone.className = "cloned";
el.parentNode.appendChild(clone);
w = clone.innerHTML.split(' ');
wrapIt();
}
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';
return;
}
if(clone.offsetWidth <= el.parentNode.offsetWidth){
//add a new word
continue;
}
//Gone too far? remove last word
clone.innerHTML = clone.innerHTML.replace(w[i], '');
el.style.width = clone.offsetWidth+ 1 + 'px';
return;
}
}