Let's say I have a DIV: <div></div>
and I want to find out with JS what its line-height is. I know one can check the style attribute style.lineHeight
, but I want to check the actual line-height, without it depending on the existence of a CSS rule.
Assuming the font family and font size are the same, both should output the same line-height:
<div>One line of text</div> <div>Two <br /> Lines of text</div>
How can I get the line-height of an element with JavaScript?
Leading is the distance between the bottom of a line of text and the top of the line of text underneath it. Line-height is the distance between half of the leading above a line and half the leading below it. To convert leading to line height: font size + (leading / 2) = line-height.
Height is the vertical measurement of the container, for example, height of a div. Line-height is a CSS property to specify the line height i.e. the distance from the top of the first line of text to the top of the second. It is the space between the lines of two paragraphs.
What is the difference between the following line-height settings? line-height: 20px; line-height: 2; The value of 20px will set the line-height to 20px. The value of 2 will set the line-height to twice the size of the corresponding font-size value.
Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.
The answer is actually using .clientHeight
. As Gaby said, this is not really reliable/trustworthy. However, it is! Here:
function getLineHeight(el) { var temp = document.createElement(el.nodeName), ret; temp.setAttribute("style", "margin:0; padding:0; " + "font-family:" + (el.style.fontFamily || "inherit") + "; " + "font-size:" + (el.style.fontSize || "inherit")); temp.innerHTML = "A"; el.parentNode.appendChild(temp); ret = temp.clientHeight; temp.parentNode.removeChild(temp); return ret; }
"Clone" the properties of your element into a new one, get the new's clientHeight
, delete the temporary element, and return it's height;
Explained at quirksmode : http://www.quirksmode.org/dom/getstyles.html
example: http://www.jsfiddle.net/gaby/UXNs2/
function getStyle(el,styleProp) { var x = document.getElementById(el); if (x.currentStyle) var y = x.currentStyle[styleProp]; else if (window.getComputedStyle) var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp); return y; }
and use it like
getStyle('test', 'line-height' )
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