0

How can I calculate the height of a div given text length and the width of a div in angular?

const containerWidth = this.container.nativeElement.offsetWidth;
let rows = text.length*fontSize/containerWidth;
rows = Math.max(1, rows );

This is my attempt, but it is adding more than needed.

hammies
  • 1,344
  • 2
  • 22
  • 46
  • Does this answer your question? [How is font size calculated?](https://stackoverflow.com/questions/3495872/how-is-font-size-calculated) – Sherif Aug 04 '21 at 16:13
  • Generally speaking it's a bad idea to equate font size to pixels. Instead of this approach try using css to solve this problem as it offers a far more intuitive way of tackling size. – Sherif Aug 04 '21 at 16:16
  • Can you explain why you need to manually set the rows ? I believe you can use flexbox with pure CSS or with bootstrap – Wasim Nabil Aug 04 '21 at 16:18
  • I have dynamic content coming in, it is using a virtual scroll and the height needs to be calculated. Unfortunately, the css box would not update the height like it would normally. The height also needs to calculate the pictures dimensions and the number of elements. – hammies Aug 04 '21 at 16:20
  • It will not answer your question. But you can make use of the DivElement.scrollHeight to get the height of your div without make any mathematical operations. – Ricardo Machado Aug 04 '21 at 16:56
  • `let rows = text.length*fontSize/containerWidth;` is incorrect. Maybe an approximation, but every letter has a different width. I suggest render the text in a new, some-way-hidden DOM element, get the height and then delete the DOM element. – Conrado Lopez Aug 04 '21 at 17:42

0 Answers0