How much content can fit in a div of a certain height and width

Suppose I have a content of 1000 words. And I have several divs of height and width 100X100, and I can create new divs of the same height and width. If i need to. how can I decide how much content is enough for one div and the rest of the content will be transferred to the next div and so on until the content ends.

+4
source share
1 answer

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
+2

Source: https://habr.com/ru/post/1652009/


All Articles