3

Here is my example code:

body {
  margin: 0;
  padding: 0;
  border: 0;
  background: #444;
}
#container {
  width: 25px;
  margin: auto;
  margin-top: 2px;
  padding-top: 1%;
  border-bottom: 3px solid #58e;
  background: #fff;
}
<div id="#container">text</div>

When I run it in chrome and inspect element the computed style of the div, the width is coming as 25px as defined above but the padding-top is coming as 13.65px.

I know that the padding-top is calculated based on % of the width of the element. So it should be 1% of 25px or 2.5px.

Why is it coming as 13.65px?

web-tiki
  • 99,765
  • 32
  • 217
  • 249
Probosckie
  • 1,585
  • 4
  • 25
  • 40

1 Answers1

9

On MDN for padding :

Percentages refer to the width of the containing block [source]

This means percentage padding is calculated according to the width of the parent element, not the element itself.

In your case padding top for #container is calculated according to the width of <body>.

web-tiki
  • 99,765
  • 32
  • 217
  • 249
  • I've been scouring SO for hours looking for an explanation of this. Thank you! Any reason percentages take the parent container width, rather than the width of the container itself (which seems like it would be more intuitive)? – jayp Jan 09 '17 at 04:29
  • 1
    @jayp it's hard to tell why the specs are the way they are. But in this case, it can become handy when you need to keep the aspect ratio of an element (see [here](http://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css)) or to have the same padding all around an element. – web-tiki Jan 09 '17 at 08:18