0

In the snippet below there are four divs with 33 characters each. Depending on the width and the word wrapping, the div can take one, two or three lines. What is a good way to calculate this beforehand?

The reason I need this is because I use a React List component (https://bvaughn.github.io/react-virtualized/#/components/List) which accepts a fixed value for the height of a list item or a function to calculate the height of a list item depending on the index. Using that index I can retrieve the text that will be in the div and get the width of the list using JavaScript. From these variables I can hopefully calculate the appropriate height.

.p100 {
  width: 100px;
}

.p150 {
  width: 200px;
}
<div id="div1" class="p100">
  Hello Hello Hello Hello Hello
</div>
<hr>
<div id="div2" class="p100">
  abcd abcd abcd abcd abcd abcd
</div>
<hr>
<div id="div3" class="p150">
  Hello Hello Hello Hello Hello
</div>
<hr>
<div id="div4" class="p150">
  abcd abcd abcd abcd abcd abcd
</div>
Michiel Borkent
  • 34,228
  • 15
  • 86
  • 149

3 Answers3

2

The reason I need this is because I use a React List component...which accepts a fixed value for the height of a list item or a function to calculate the height of a list item depending on the index.

Hi :) Author of react-virtualized here.

I think you should check out the CellMeasurer component. I created it for use cases like the one you're describing. Check out a demo here and docs here.

Essentially, CellMeasurer would allow you to defer measuring your text until runtime. List could use an estimated size until then for rows that aren't yet visible.

bvaughn
  • 13,300
  • 45
  • 46
0

It almost seems that you are saying you want to know how much lines you have left before the words overlap you divs.

If that is the case you can change the width to width:auto or set it to 100%. This way, it will expand with your 'lines'.

0

By jquery you can have width and height of each div by:

$('#the-div-id').width();
$('#the-div-id').height();

and javascript:

document.getElementById('the-div-id').clientWidth;
document.getElementById('the-div-id').clientHeight;
Farzin Kanzi
  • 3,380
  • 2
  • 21
  • 23