Why font-family sporadically adds 1px gap between buttons?

后端 未结 8 942
小蘑菇
小蘑菇 2020-12-16 12:13

Please read the question carefully. It\'s not the same as the one about How to remove the space between inline-block elements.

Consider the followin

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 12:51

    The answer assumes that DirectWrite is enabled. You will not notice the specified symptoms and fractional widths otherwise. It is also assumed that default serif and sans-serif fonts are Times New Roman and Arial.


    Whoever said that the space character is 4px wide is mistaken:

    $(function() {
        $(".demo").each(function() {
            var width = $("span", this).width();
            $("ins", this).text("total width: " + width + "px, " + (width / 10) + "px per space)");
        });
    });
    .demo {
        white-space: pre;
        overflow: hidden;
        background: #EEE;
    }
    .demo-1 {
        font: 16px/1 sans-serif;
    }
    .demo-2 {
        font: 16px/1 serif;
    }
    .demo-3 {
        font: 16px/1 monospace;
    }
    .demo span {
        float: left;
        background: #CF0;
    }
    .demo ins {
        float: right;
        font-size: smaller;
    }
    
    

    The green blocks contain 10 spaces:

    Note that:

    1. For a given size the character width depends on font family.
    2. The character width does not necessarily have to be a whole number. Serif font gives you a nice whole number (4px), but Sans-serif font gives you fractional number (4.4px).

    You could get different results in different browsers depending on how they handle fractional gaps between two blocks (e.g. 4.4px for 16px Arial). CSS specs are silent about this.

    In Chrome with DirectWrite enabled, spaces are rendered as 4px and 5px alternately due to rounding off. This explains why there is no gap between first and second button and 1px gap between second and third. Try adding more buttons in your original example and notice how the pattern repeats (Demo).

    Using margin-left: -4.4px seems to work but it is not guaranteed to work. Consider going back to the alternate solutions.

提交回复
热议问题