Home > Software design >  getting the height of the text in a fixed height div
getting the height of the text in a fixed height div

Time:11-26

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/

CodePudding user response:

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();

CodePudding user response:

Hope this trick works for you.

<div style="width: 100px; height: auto; min-height:100px; background: yellow; font-size: 30px">
 hello, world! hello, world! hello, world!
</div>
<br/>
<div style="width: 100px; height: auto; min-height:100px; background: yellow; font-size: 30px">
 hello, world! test
</div>
<br/>
<div style="width: 100px; height: auto; min-height:100px; background: yellow; font-size: 30px">
 hello, world! testing data
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related