Why are margin/padding percentages in CSS always calculated against width?

后端 未结 5 1789
迷失自我
迷失自我 2020-11-22 17:07

If you look at the CSS box model spec, you\'ll observe the following:

The [margin] percentage is calculated with respect to the width

5条回答
  •  再見小時候
    2020-11-22 17:48

    I vote for the answer from @ChuckKollars after playing with this JSFiddle (on Chrome 46.0.2490.86) and referring to this post (written in Chinese).


    A major reason against the infinite calculation conjecture is that: using width faces the same infinite calculation problem.

    Have a look at this JSFiddle, the parent display is inline-block, which is eligible to define margin/padding on it. The child has margin value 20%. If we follow the infinite calculation conjecture:

    1. The width of the child depends on the parent
    2. The width of the parent depends on the child

    But as a result, Chrome stops the calculation somewhere, resulting:

    If you try to expand the "result" panel horizontally on the JSFiddle, you will find that the width of them will not change. Please note that the content in the child is wrapped into two lines (not, say, one line), why? I guess Chrome just hard-code it somewhere. If you edit the child content to make it more (JSFiddle), you will find that as long as there is extra space horizontally, Chrome keeps the content two lines.

    So we can see: there is some way to prevent the infinite calculation.


    I agree with the conjecture that: this design is just to keep the four margin/padding values based on the same measure.

    this post (written in Chinese) also proposes another reason is that: it is because of the orientation of reading/typeset. We read from top to down, with the width fixed and height infinite (virtually).

提交回复
热议问题