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

后端 未结 5 1794
迷失自我
迷失自我 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:42

    I know this question is a bit old, but I'd like to refresh it for CSS3. While it's true that the CSS2.1 specification says that percentage padding and margin are defined relative to the width of the containing block, this is not always the case. It depends on the writing mode. This comes straight from the CSS3 specs:

    As a corollary, percentages on the margin and padding properties, which are always calculated with respect to the containing block width in CSS2.1, are calculated with respect to the inline size of the containing block in CSS3.

    I cover this in my tutorial on aspect ratios with CSS.

    Specifically, there's a section on Percentage Padding in Horizontal vs. Vertical Writing Modes. By default, an element has a horizontal writing mode, where text flows horizontally (in the "inline" direction) from left to right. However, using the writing-mode CSS property, you can actually set the mode to be vertical (with text either flowing from right to left or left to right). Here are some diagrams of horizontal vs vertical writing modes:

    A horizontal writing mode, with text flowing vertically from top to bottom. An arrow points from left to right at the top of the document and is labeled as the inline direction. Another arrow points from top to bottom and is labeled as the block direction.

    A vertical writing mode, with text flowing horizontally. The horizontal axis is labeled as the block direction, whereas the vertical axis is now labeled as the inline direction. Text is rendered sideways.

    These are taken from the MDN docs on writing modes.

    In vertical writing modes, percentage padding will be relative to the height of the containing block, not to the width.

    Here's proof:

    .document {
      writing-mode: vertical-rl;
      width: 100%;
      height: 100vh;
    }
    
    .parent {
       width: 100%;
       height: 200px;
       background-color: black;
       color: white;
    }
    
    .child {
      padding: 10%;
      background-color: white;
      color: black;
      border: solid 1px;
    }
    Child

    The child gets 20px of padding, which is 10% of its containing block's height (200px).

    As to the why in the question, this was covered well in the other posts here.

提交回复
热议问题