Tbi45
Tbi45

Reputation: 607

Set margin sizes with `%`... Parent or element relativity?

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?

Upvotes: 0

Views: 231

Answers (1)

Terry
Terry

Reputation: 66103

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.

Upvotes: 1

Related Questions