Vertical alignment of text in container: WebKit vs Firefox

Olaj picture Olaj · May 4, 2011 · Viewed 15.2k times · Source

The problem is that Firefox and WebKit based browsers seem to align text vertically in different ways when contained in an element that has an even height/line-height and the font-size is uneven (or vice versa). I have looked at some similar threads, but I haven't really seen any great explanations for my question.

Consider the following example:

.box {
  font-size: 15px;
  font-family: Helvetica, Arial;
  background-color: Blue;
  height: 20px;
  width: 60px;
  color: White;
  line-height: 20px;
}
<div class="box">
  A text.
</div>

Example showing vertical alignment difference between Firefox and Chrome.

Is there any way to fix this? Is there any "text-align" property or something that I missed?

Answer

Boris Zbarsky picture Boris Zbarsky · May 4, 2011

This is due to differences in how browsers handle subpixel text positioning. If your line-height is 20 pixels but font-size is 15 pixels, then the text needs to be positioned 2.5 pixels from the top of the line box. Gecko actually does that (and then antialiases or snaps to the pixel grid as needed on painting). WebKit just rounds positions to integer pixels during layout. In some cases, the two approaches give answers that differ by a pixel. Unless you're comparing them side-by-side, how can you even tell there's a difference?

In any case, making sure that your half-leading is an integer (i.e. that line-height minus font-size is even) will make the rendering more consistent if you really need that.