I agree with the commentators on the fact that there are usually better ways, and such an idea will work slowly and, of course, not everywhere (JavaScript for layout is often a signal of problems in the page architecture).
However, there is a solution for this.
, 100x100 . div width: 100px, height: auto , offsetHeight 100. , , , , . lorem ipsum, 100x100, . , , .
var loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.'
var boxParent = document.getElementById('parent');
while (loremIpsum.length > 0) {
var boxContent = document.createElement('div');
boxContent.className = 'content __measuring';
boxParent.appendChild(boxContent);
var indexOfSpace = loremIpsum.indexOf(' ');
var lastIndexOfSpace = indexOfSpace;
while (indexOfSpace != -1 && boxContent.offsetHeight < 100) {
boxContent.innerHTML = loremIpsum.substring(0, indexOfSpace);
lastIndexOfSpace = indexOfSpace;
indexOfSpace = loremIpsum.indexOf(' ', indexOfSpace + 1);
}
if (indexOfSpace == -1) {
boxContent.innerHTML = loremIpsum;
loremIpsum = '';
}
else {
loremIpsum = loremIpsum.substring(lastIndexOfSpace + 1);
}
boxContent.className = 'content';
}
#parent .content {
display: inline-block;
width: 100px;
height: 100px;
padding: 8px;
margin: 8px;
background: yellow;
font-family: Arial, sans-serif;
font-size: 16px;
box-sizing: border-box;
vertical-align: top;
}
#parent .content.__measuring {
height: auto;
}
<div id="parent">
</div>
Hide result