Why does a percentage margin cause a new line?

后端 未结 3 696
日久生厌
日久生厌 2021-02-04 07:04

      
3条回答
  •  我在风中等你
    2021-02-04 07:28

    Unfortunately, the CSS2.1 spec doesn't appear to have a clear answer to this. In fact, I would say this is well within the realm of undefined behavior.

    Here are the relevant points I can find:

    • Floats without a specified width will shrink to fit their contents. In the case of floats with only inline content, the float needs to be made just wide enough to fit its contents on a single line (notwithstanding explicit line breaks) and no more.

    • Percentage margins are calculated based on the width of the containing block.

      Note that it says:

      If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.

      ... but as far as I can see, the behavior is consistent across all browsers.

      That being said, the reason this statement applies is because since the margin of the inline element falls within the content bounds of the float, it can be said that the width of the float (the containing block of the inline elements) depends on the this element (the element having the margin).

    Here's what I can deduce based on the points above:

    • When the margin is specified as a percentage, the width of the float is calculated without taking the margin into account, because it's not possible to calculate the margin until the width of the float has been determined.

      The margin is then calculated based on the used width of the float, and the letter "c" wraps to a new line as a result of being pushed forward by the margin on "a". The width of the float does not change.

      Again, none of this behavior is specified at all, and so technically it's not in violation of the spec. However, it seems sensible.

    • When the margin is specified as a pixel value, the margin is calculated first. The width of the float is then calculated taking this margin into account (remember that horizontal margins do apply to inline elements as normal). Per the shrink-to-fit algorithm, this is the preferred width: just wide enough to contain all the inline elements on a single line.

      Unlike with percentage margins, this is very clear-cut, as implementations should have no trouble calculating computing absolute values for margins first.

    I would be hard-pressed to call this a bug in any of the browsers, especially since they all behave consistently.

    Lastly, of course, you can avoid this undefined behavior entirely simply by giving your floats explicit widths where possible. It does help to understand why you should do so, however.

提交回复
热议问题