How to get consistent line-heights between browser

2019-08-09 14:07发布

问题:

This question is basically an extension of this one about an issue I was having with vertical centering. Finding the answer to that question created a need for this question.

Have a look at this JSFiddle. It sets up a container to be 60px tall.

.container {
    background-color: lightgreen;
    height: 60px;
    max-height: 60px;
    line-height: 60px;
    font-size: 60px;
}

In Firefox, it is 60px tall in all cases. In Chrome, the text height is actually taller than 60px (sometimes 69px, sometimes other values).

I can reduce the font-size to 52px to get it to line up as exactly 60px tall in Chrome (thus giving me a perfectly 60px tall inline element and allowing me to vertically center reliably) but that is specific not only to Chrome, but to the computer.

How can I get a consistent font height?

回答1:

If you try

font-size: 3.29em;

Does that work across browsers?



回答2:

Each browser has it's own preset styles that you might need to override. Set this at the top of your css to remove any defaults:

html, body, div, span, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, em, img, strong, sub, sup, b, i, dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figure, figcaption, footer, header, hgroup, 
menu, nav, output, section, time {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}

And then style however you wish after.



回答3:

I was having similar issues with texts contained in buttons and input fields. If you are using web font services like Fontsquirrel, as I am, make sure you check the font optimization option "Vertical Metrics" to "No Adjustment", under Expert Mode. Fontsquirrel defaults seems to mess up with these things.