Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the line height of a span?

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.

like image 267
Radan Ganchev Avatar asked Dec 22 '11 16:12

Radan Ganchev


People also ask

How do you find the height of a span?

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.

How is line height calculated?

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.

How do you find the width and height of a span?

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”.

Does span have height?

Span is an inline element. It has no width or height.


2 Answers

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.

like image 167
Ashh640 Avatar answered Sep 17 '22 08:09

Ashh640


$("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.

like image 23
Esailija Avatar answered Sep 19 '22 08:09

Esailija