I wasnt satisfied with the answers here and on other questions. The highest rated answer doesn't take padding
or border
into account, and therefore obviously ignores box-sizing
as well. My answer combines some techniques here and and on other threads to get a solution that works to my satisfaction.
It isnt perfect: When no numerical value was able to be retrieved for the line-height
(e.g. normal
or inherit
), it just uses the font-size
multiplied by 1.2
. Perhaps someone else can suggest a reliable way to detect the pixel value in those cases.
Other than that, it has been able to correctly handle most of the styles and cases I have thrown at it.
jsFiddle for playing around and testing. Also inline below.
function countLines(target) {_x000D_
var style = window.getComputedStyle(target, null);_x000D_
var height = parseInt(style.getPropertyValue("height"));_x000D_
var font_size = parseInt(style.getPropertyValue("font-size"));_x000D_
var line_height = parseInt(style.getPropertyValue("line-height"));_x000D_
var box_sizing = style.getPropertyValue("box-sizing");_x000D_
_x000D_
if(isNaN(line_height)) line_height = font_size * 1.2;_x000D_
_x000D_
if(box_sizing=='border-box')_x000D_
{_x000D_
var padding_top = parseInt(style.getPropertyValue("padding-top"));_x000D_
var padding_bottom = parseInt(style.getPropertyValue("padding-bottom"));_x000D_
var border_top = parseInt(style.getPropertyValue("border-top-width"));_x000D_
var border_bottom = parseInt(style.getPropertyValue("border-bottom-width"));_x000D_
height = height - padding_top - padding_bottom - border_top - border_bottom_x000D_
}_x000D_
var lines = Math.ceil(height / line_height);_x000D_
alert("Lines: " + lines);_x000D_
return lines;_x000D_
}_x000D_
countLines(document.getElementById("foo"));
_x000D_
div_x000D_
{_x000D_
padding:100px 0 10% 0;_x000D_
background: pink;_x000D_
box-sizing: border-box;_x000D_
border:30px solid red;_x000D_
}
_x000D_
<div id="foo">_x000D_
x<br>_x000D_
x<br>_x000D_
x<br>_x000D_
x<br>_x000D_
</div>
_x000D_