0

is there a way we can get the width of a simple string- I know with the HTML markup its possible via the getting the id from the dOM and then checking the width on that element. however in my case its rendering as a string value and I need to know the width of that string in order to add ellipses based on that. I can do it via CSS, however in CSS I'll have to define the width in order to get the ellipsis. I need to have customize width based on points rendered on a chart. is this even possible?

I tried length

var string = "Hello world- need to know width";
var len = string.length;

but im not sure of this is equivalent of width.

user1234
  • 3,000
  • 4
  • 50
  • 102
  • You can't tell the width until it's rendered, because it depends on the element that you're rendering it in, and its CSS. – Barmar Oct 05 '20 at 23:28

1 Answers1

0

The actual width of rendered text is dependent on some factors including font-size and font-family, current zoom level and ... thus if need to apply some style like ellipsis you need to get real rendered size; I am not aware any other way than actually rendering it screen and reading the size with javascript; ( you can render it on a newly created opacity:0 element and after calculation destroy it or other similar ways).

by the way in this web.dev article they'd explained how text nodes can be considered as lcp in some cases which can give you insights of how text nodes rect can be calculated; you can also check this SO answer

Mechanic
  • 5,015
  • 4
  • 15
  • 38