Reputation: 1630
I want a child div with a op-margin via percentage. The y-position shall be 50% percent of the parent div. But it is somehow more. Why isn't it 50% ?
HTML
<div class="content">
<header></header>
</div>
CSS
.content {
width: 300px;
height: 200px;
background: blue;
position: relative;
clear: both;
}
.content header {
width: 100px;
height: 100px;
margin-top: 50%;
background: red;
position: relative;
float: left;
}
Upvotes: 11
Views: 28163
Reputation: 15412
Change child's position from relative to absolute.
Instead of margin-top
use top
.content header {
top: 50%;
position: absolute;
}
Upvotes: 5
Reputation: 66218
This is because when it comes to top/bottom margins and paddings in percentages, the values will be taken as the fractional width of the parent element, not the height. According to the W3C definition:
The [margin] percentage is calculated with respect to the width of the generated box's containing block. Note that this is true for 'margin-top' and 'margin-bottom' as well. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.
This question has been addressed before in StackOverflow - see here.
Suggestion: If you would want to position an element in the center vertically, you can use the following trick instead:
Here's the modified CSS from your fiddle that works:
.content header {
width: 100px;
height: 100px;
top: 50%;
background: red;
position: absolute;
-webkit-transform: translate(0, -50%);
transform: translate(0, -50%);
}
http://jsfiddle.net/teddyrised/73xkT/7/
Upvotes: 23