-->

Vertical alignment text in container WebKit vs Fir

2019-01-21 20:54发布

问题:

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

Consider http://alternativeto.net/test2.htm. This is a really simple page with just

    .box
    {
        font-size: 15px;
        font-family: Helvetica, Arial;
        background-color: Blue;
        height: 20px;
        width: 60px;
        color: White;
        line-height: 20px;
    }

And

    <div class="box">
        A text.
    </div>

If you open that page up in Chrome and Firefox you notice that they align the texts in different ways: http://screencast.com/t/tjgA2d7T

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

回答1:

This is browser rendering issue. Use line-height 1px less than the given height, for example:

    .box
{
   background-color: Blue;
   color: White;
   font-family: Helvetica,Arial;
   font-size: 15px;
   height: 18px;
   line-height: 17px;
   width: 60px;
}


回答2:

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.



回答3:

If you are looking for a way to do an exact vertical align, check out Stack Overflow question Problem with vertical-align: middle; - I described a solution there.

If you want an answer why Firebug and Chrome display this differently, this will be a bit more complicated. Line-height alignment is based on font-line rendering and fonts can be handled in a very different way across the browsers. For example, font-smoothing and font-weight can really mess with your page.

Also, are you using CSS reset for this page? It contains font related adjustments as well, and it may help you to overcome cross-browser issues. Refer to CSS Tools: Reset CSS.



回答4:

Ugh, terrible but true! I just ran into this trying to create tiny count bubbles on an icon - so small that I had to get right next to text so every pixel counted. Making the line-height 1x less than text-size leveled the display field between FF and Chrome.