Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertical alignment of text in container: WebKit vs Firefox

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?

like image 394
Olaj Avatar asked May 04 '11 08:05

Olaj


People also ask

How do I vertically align text in a container?

The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.

Does vertical-align work for text?

The vertical-align property can be used in two contexts: To vertically align an inline element's box inside its containing line box. For example, it could be used to vertically position an image in a line of text. To vertically align the content of a cell in a table.

What is the difference between Valign and text-align?

valign will vertically align all elements, whereas text-align is specifically for text.


1 Answers

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.

like image 196
Boris Zbarsky Avatar answered Sep 23 '22 19:09

Boris Zbarsky