Reputation: 626
Suppose I have content of 1000 words. And I have multiple divs of 100X100 height and width and I can create new divs of the same height and width If I need. how do I decide that how much content is enough for one div and the rest of the content will be moved to the next div and so on until the content ends.
Upvotes: 4
Views: 732
Reputation: 2135
I agree with commenters on your question that usually there are better ways and such an idea is going to work slow and certainly not everywhere (JavaScript for layout is often a signal of problems in the page's architecture).
However, there is a solution for this.
You will need to measure how many words fit in 100x100 box and slice the content in appropriate way. For this, you may use an invisible div
with width: 100px
but height: auto
and add content there until its offsetHeight
becomes greater than 100
. Since you probably use a normal font and not a monospaced one, the measurement will need to take place for every box. In the following example, we will slice lorem ipsum
text to fit into as many 100x100 boxes as needed. It is not quite optimized and you may need further work on it to suite your purposes.
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>
Upvotes: 4