Reputation: 33
I'm working to center #child within #parent at 100% height and width. Why does setting the #child top position to 10% work, but using 10% as a margin-top does not?
http://jsfiddle.net/rbtstudio/SCmfG/
<style>
html {
height: 100%;
}
body {
height: 100%;
overflow: hidden;
}
#parent {
width: 100%;
height: 100%;
background-color: #323232;
}
#child {
width: 80%;
height: 80%;
background-color: #eaeaea;
margin: 0 auto;
position: relative;
top: 10%;
}
/*
#child {
width: 80%;
height: 80%;
margin-top: 10%;
margin-right: auto;
margin-bottom: 0;
margin-left: auto;
}
*/
</style>
<div id="parent">
<div id="child"></div>
</div>
Upvotes: 2
Views: 109
Reputation: 78690
The issue here is called "collapsing margins". You can read more about them in the css spec.
http://www.w3.org/TR/CSS21/box.html#collapsing-margins
It's not that the margin isn't working, it's that the margin is collapsing, causing the margin to apply to the top of the parent box.
You'll notice that when the margin is applied to the child, the parent is moved down.
One workaround (of many) to avoid the collapsing of margins is to add overflow: hidden
to the parent element:
EDIT: Another important point to keep in mind (which was in another answer which has since been deleted) is that all percentage margins are based on a percentage of the width of the element, even top and bottom.
Upvotes: 3