0

Let's say we have the following HTML:

<div id='parent'>
   <div id='child'>
   </div>
</div>

If we set this CSS :

 #parent {
     width:1000px;
     height:1000px
 }
 #child {
    width:20%;
    height:40%;
    margin-top:10%;
 }

The child element will have a margin-top that will be a % of the parent height or the child height? Also there is a different way that browsers render the % sizeing when it comes to margins ? If there is a padding applied to child/parent , it will influence the margin?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Tbi45
  • 607
  • 2
  • 6
  • 14

1 Answers1

1

The best way to check is it test it out yourself ;)

All percentages with regards to width, height are calculated based on the parent container's width - in this case, the #child element will have a width of 200px and height of 400px.

Meanwhile, paddings and margins, when percentage-based, are calculated from the containing parent's width: therefore #child will have a top margin of 100px.

Do take note that vertical margins (i.e. the top and the bottom margins) may collapse under some circumstances. In the fiddle that I have posted, this is exactly the case.

Community
  • 1
  • 1
Terry
  • 63,248
  • 15
  • 96
  • 118
  • Proof: http://jsfiddle.net/8Jcdu/ with function from [here](http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/) – Simon Apr 12 '13 at 10:15
  • 1
    _"It is important to note that height, when specified in percentages, refers to the percentage width of the parent element (not the height)."_ Could you pls quote that from the docs? This seems very misleading to me (percentage height calculated from parent's width? Not really...) and I couldn't find such a statement in the docs. – Simon Apr 12 '13 at 10:19
  • Directly from the W3C link: _"The percentage is calculated with respect to the height of the generated box's containing block."_ – thgaskell Apr 12 '13 at 10:22
  • My bad - I mixed up some thing. I meant margins and paddings are calculated based on containing parent's width when specified in percentages. Had a brain fart :P – Terry Apr 12 '13 at 10:23