I’m taking a designers specs and converting them into HTML/CSS. I keep running into the same problem though – the designer will spec a rectangle with some text centered vertically in it. He’ll specify the height of the rectangle at 36 pixels and the font at 18px. I’ll create a 36 pixel DIV with no border and 9 pixel padding-top (using box-model built into bootstrap). The text is always too far down though. It looks like the text is bigger than 18 pixels. Taking a screenshot and measuring in Photoshop shows the text is 20 pixels high.
Am I missing something? Are pixels inconsistent from screen to screen? Is a font pixel different than a screen pixel? I’ve read fonts should be in points now for high DPI screens. Does it matter?
3
Answers
Pixels are different from screen to screen. Pixels on some screens are larger than others. Some screens have more pixels than others. This can be an issue especially when defining
width
andheight
properties.ex
andem
will stay consistent (in relative space not actual size) no matter what the screen size or pixel count is.Example uses:
Height: 10ex;
Width: 10ex;
This is a good article explaining all of this in depth.
An 18px font of one type is not necessarily the same height as 18px of another font. You can have ascenders and descenders that can make a font look bigger but the CSS font size does not take that into consideration. So we need to see which font you’re using but trying to center based on font size rarely works and is unreliable if you were to change the font at a later date.
The font size doesn’t correspond exactly to the height of the text, it’s a somewhat arbitrary value that is chosen to reflect the size of the font. Fonts of different style may have slightly different actual sizes in order for them to appear similar in size.
Adding to this, different browsers calculate font sizes slightly differently, so the actual size may differ a pixel or so between browsers.
Also, the font size is not including the line height, which by default adds something like 20% to the height.
What I usually use to center a line vertically in an element, is to set the line height to the height of the element. Example: