使用百分比 (%) 时如何计算填充?

How is padding calculated when using percentage (%)?

为什么这个例子中的padding不等于300px?

#Test{
  width:600px;
  padding-right:50%;
  box-sizing:border-box;
  background:#ddd;
}
<div id="Test">
TEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ H
</div>

注意:我不只是在寻找解决方案,而是要了解填充在这里的工作方式。

TL;DR

The padding is calculated according to the parent's width


首先,您应该注意:

Percentage:
The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3c, emphasis mine)

这表示padding是根据父元素宽度计算的(需要注意的是,在non flexbox layouts中,padding top和bottom是也相对于包含块的宽度).

与box-sizing:border-box

当您更改默认值 box-model to border-box 时,填充(和边框)包含在元素的宽度中,就像您的示例中一样。所以用

width:600px;
padding-right:50%;
box-sizing:border-box;

右内边距必须是父级宽度的 50%,但元素的总宽度为 600 像素。填充右为元素宽度的 50% 的唯一时刻是 parent width = element width请注意,这在您的示例中不会发生,因为父项是 body 并且 body 具有默认边距).

解决方法:
如果你希望 padding 为元素宽度的 50%,在这个盒子模型中你可以:

  • 设置固定填充:width:600px; padding-right: 300px;
  • 给元素一个流动的宽度:width:50%; padding-right:25%;

没有box-sizing:border-box

在默认 box-model 中,填充不包含在元素的宽度中,因此 element width = 600px + 50% of parent's width 如您在以下示例中所见:

#Test{
  width:600px;
  padding-right:50%;
  background:#ddd;
}
<div id="Test">
TEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ HTEXT ETISI DHOASIHD I SAIDUHSILAUDH LISH ADBHSJADB JHSA DKH ASKDH KSAH DKLJS ADLK ASJKLD KLASH DLSJAH KLS ADKL S JS KSH KD KSJ HDKJSH DKH SDKH SKDH KSJH DKJSH DKJ H
</div>

解决方法:
如果你希望 padding 为元素宽度的 50%,在这个盒子模型中你可以:

  • 设置固定填充:width:300px; padding-right: 300px;
  • 给元素一个流动的宽度:width:25%; padding-right:25%;

参考文献:

它与父元素的宽度有关,除非父元素的宽度取决于此。

来自 W3C 的 CSS 2.1 Specification:

The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.