7

I have the following code:

    .parent {
      width: 30%;
      border: 1px dotted red;
    }

    .child {
      padding-top: 100%;
      border: 1px solid black;
    }
 <div class="parent">
      <div class="child"></div>
    </div>

And for some reason the child becomes a perfect square. This is at least weird because none of the divs have any height assigned to them. Why is this happening?

What does padding-top: 100% do?

Fiddle

iuliu.net
  • 6,666
  • 6
  • 46
  • 69
  • 4
    padding-bottom: 100% means "make the padding bottom as tall as the element's width", thus, it's a square, more info here: https://www.w3.org/TR/CSS2/box.html#padding-properties – Jonas Grumann Oct 18 '16 at 11:34
  • 4
    The percentage is computed on the *width* of the parent container. This is a commonly used trick to get proportionally scaled width *and* height thumbnails. – user229044 Oct 18 '16 at 11:36
  • Thanks for clarifying @meagar. This doesn't make much sense to me, but it seems to be just what's happening. – iuliu.net Oct 18 '16 at 11:40
  • https://stackoverflow.com/questions/11003911/why-are-margin-padding-percentages-in-css-always-calculated-against-width – user229044 Oct 18 '16 at 11:40
  • It makes NO sense, but it's the only solution for retaining aspect ration, regardless of width, that does not require JavaScript manipulation. AFAIK. I use `width:100%, padding-top:100%` on parent, then child img has `width:100%, height:100%, object-fit:cover, object-position:center, border-radius:50%` to make perfect circle thumbs for example. – s3c May 21 '20 at 10:43

2 Answers2

12

Your child div is filling parent in 100% width. Padding-top property in percent is determined by div width. So, your child is getting 100% width of parent (30%) and padding top 100% means 100% width of that element. The same applies to margin-top which is calculated by width.

User1493
  • 481
  • 2
  • 7
  • 23
Alan Mroczek
  • 1,099
  • 1
  • 11
  • 27
-1

The padding-top: 100% on the child makes it a perfect square because the child has a height of 0px and therefore the padding on the top is the only thing that takes up space.

Therefore if the height wouldn't be 0, then you would not end up with a perfect square.

weiyolan
  • 1
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 04 '23 at 11:20
  • Although your answer doesn't really explain why it produces a perfect square, you rightly point out the role of the 0px height of the child. – Marcus Gambit Aug 26 '23 at 14:46