17

Referring go this example
http://jsfiddle.net/uzgJX/

The result is the height of the box containing the text (the one you can see if you select the text with the mouse..) wichi is higher then the real height of the text.
Is there a way to get the real height with jquery or plain js?
In the example I tryed with

text.height()

and

text[0].getBoundingClientRect().height  

with no luck, it says 19px instead of 14px

ettolo
  • 277
  • 1
  • 3
  • 11
  • check this out: http://stackoverflow.com/questions/1134586/how-can-you-find-the-height-of-text-on-an-html-canvas – vector Mar 01 '13 at 15:50
  • sorry fgokalp: made some errors wile typing and editing the question, refer to the answer and fiddle examle of Andy E Below – ettolo Mar 01 '13 at 21:50
  • tanks vector, i've to read you link, but andy's answer seem to be simpler – ettolo Mar 01 '13 at 21:58

1 Answers1

17

Get the computed font-size for your text element instead:

parseInt(window.getComputedStyle(text[0]).fontSize, 10);

font-size represents the size of an em square for a font. It should be noted that, while most glyphs will stay inside the bounds of an em square, some may exceed those bounds. This doesn't usually occur on the vertical dimentions, though.

Give it a try: http://jsfiddle.net/uzgJX/1/. Tip: screenshot and copy into your favourite image editor, then select the pixels exactly to the height of the text and compare with the value given in the fiddle.

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • @ettolo: in the case where text is not visible, you might want to check jQuery's result for `height` is greater than 0 first. – Andy E Mar 04 '13 at 09:59
  • @ettolo: no, all I see are 3 rounded rectangles that are empty. (Chrome 27 and Firefox 19 on Ubuntu) – Andy E Mar 04 '13 at 10:05
  • @ettolo: strange... it doesn't seem to work when the font-size is inherited (although it should). If I set the font-size directly on the element via CSS it works: http://jsfiddle.net/ynfAP/4/. It must be an SVG thing, since both Firefox and Chrome exhibit the same behaviour. – Andy E Mar 04 '13 at 10:16
  • @AndyE, your solution does not work. It just shows the height of a single line. What if there are multiple lines?! Then it still shows the same value: http://jsfiddle.net/uzgJX/362/ – Black Nov 14 '18 at 15:26