Is there a way to get the line-height
of a span
(or other inline element) in JavaScript/jQuery?
I need the exact computed line-height
in pixels, not values of the sort 1.2em
, normal
or heuristics like fontSize * 1.5
.
What I need to do is stretch the background of a span
to fill the whole height of the line. I figured that I could add paddings to stretch the span, but for this I need the exact line-height
. If someone can offer another approach, this would also be helpful.
Use window. getComputedStyle(mySpan). lineHeight to get value of line height of the element irrespective of whether the style is defined inline or in external CSS file. Save this answer.
It takes the font-size value and multiplies it by 1.2 . Let's calculate the height of one line with the following example. We just have to do the following calculation: 16 * 1.5 = 24px. So we now know that our text will have a minimum height of 24px.
In CSS, set the width and height of the span using the “display” property. To do so, use the “span” to access it. After that, set the value of the display property as “block” and its width and height as “400px” and “150px”.
Span is an inline element. It has no width or height.
An easy way to do this is:
var style = window.getComputedStyle(element);
var lineHeight = style.getPropertyValue('line-height');
This will get the calculate value of the line height without using jQuery and works on all browsers from IE9 onwards.
$("span").css( "line-height");
Retrieves the computed px value as a string "16px" for example. It uses IE's currentStyle
or the standard getComputedStyle
under the covers. Which is kind of surprising seeing as when it works as a setter it does elem.style.something = value
which is a whole different thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With