I'm trying to pin down exactly what px
means to font-size in terms of allocated space on the page, and the results I'm getting don't match my expectations.
I was under the impression that using pixels in conjunction with font-size
meant that the vertical space taken up by the typography would match the value specified. For example, if I specified font-size: 16px
, a line of text with that rule applied would have a height of 16px
. Please note that I was not expecting the actual glyph to be 16px
in height, but that the browser would allocate 16px
to display the glyphs.
Here's some code to use as a reference so I can explain what I expected to see vs. what I'm actually seeing:
.style-it {
box-sizing: border-box;
margin: auto;
width: 500px;
height: 500px;
border: 5px solid black;
padding: 20px;
font-size: 150px;
font-family: sans-serif;
}
<html>
<div class="style-it">
<div>
CSS
</div>
<div>
IS
</div>
<div>
AWESOME
</div>
</div>
</html>
I have a static height of 500px
set on my style-it div
, which has a 5px border
and 20px padding
. Therefore, the content of my div
has a height of 450px
. With my previous understanding of font-size
and px
, I would expect three lines of text at a font-size
of 150px
to fill that 450px
of content perfectly, but that isn't the case.
I've placed each line of text into their own div
so we can clearly see that each line is slightly larger (173px
in Chrome) than my 150px
specification.
So, what's going on here? Is it that the glyphs themselves actually are 150px
in height and the "box" around them adjusts arbitrarily based on some internal browser rule?
Is there a way that I would be able to know for sure that "I have container that is Xpx
tall and I can fit Y lines of text perfectly in there by setting their font-size
to Zpx
"?
Just an interesting problem that I came across that I couldn't find a good answer to. I don't know if it's terribly useful in the real world, but I was interested to see if anyone could answer nonetheless.
EDIT: I should have been a little clearer on what I was asking. I'm not having trouble figuring out how to fit the text inside the div, but rather interested in why, as the duplicate linked article states, the font-size
value is not the same size as the em-square
. In other words, why is specifying a line-height
of 1em
even necessary in a situation like this?
For anyone who comes across this, the linked question has a great article that is just the sort of thing I was looking for: http://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align#lets-talk-about-font-size-first