Skip to content
Advertisement

getting the height of the text in a fixed height div

Say I have this code:

<div style="width: 100px; height: 100px; background: yellow; font-size: 150px">
 X
</div>

With a font-size of 150px it’s none to surprising that the text inside the div would be bigger than the div itself. At least in Google Chrome it is.

My question is… how might I go about figuring out the height / width of the text within a fixed size div?

Using jQquery, $(...).height() returns 100 as does $(...).innerHeight() and $(...).outerHeight().

I mean, using this example, it’s pretty straight forward. The height is probably 150px. But it gets more complicated when you do something like this:

<div style="width: 100px; height: 100px; background: yellow; font-size: 30px">
 hello, world! hello, world! hello, world!
</div>

Any ideas?

https://jsfiddle.net/p0xLv1qj/

Advertisement

Answer

Well, you can create a new element containing only the text, adding it for a short period of time to your body, and then getting the height.

This is what I came up with – it returns 204 with a font size of 30:

var newEl = document.createElement("p");
newEl.innerHTML = document.getElementById("myDiv").innerHTML;
newEl.style.fontSize = document.getElementById("myDiv").style.fontSize;
newEl.style.width = document.getElementById("myDiv").style.width;
document.body.appendChild(newEl);
alert(newEl.clientHeight);
newEl.remove();
Advertisement