Why does a percentage margin cause a new line?

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

      
3条回答
  •  误落风尘
    2021-02-04 07:30

    Since your div is floated, and its width is auto (implicitly), http://www.w3.org/TR/CSS21/visudet.html#float-width applies:

    If 'width' is computed as 'auto', the used value is the "shrink-to-fit" width.

    “shrink-to-fit” width basically means, let the element be as wide as its content requires it to be.

    Now without the margin-left, that is no problem: All three of your a elements are inline elements that contain a specific character each – easy enough to determine their individual widths, and add them up.

    But now you want a margin-left in percent, and here things get complicated – if we look at the definition for margin-left, it says:

    Percentages: refer to width of containing block

    Now, that leaves us in a bit of a pickle, since the width of the containing block (which is established by the floated div element), is computed based on its content – but now this margin-left would change the overall width of that content, but is in itself dependent on the width of the containing block, which it itself influences …

    That’s a classical problem of two measurements that are dependent on each other … and that is therefor basically unsolveable.

    http://www.w3.org/TR/CSS21/box.html#margin-properties says,

     The percentage is calculated with respect to the width of the generated box's containing block. […]
    If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.


    Edit: Basically the same as what BoltClock said in his answer, just took me a little longer …

提交回复
热议问题