I'm trying to vertically center content in a fixed-height <div>
.
I'm using the technique of top:50%
and transform:translateY(-50%)
to do this, but I cannot understand why the margin
of the child elements are not being taken into account, but the padding
is.
If you run the snippet below, you can see the contents of the left box (where the <p>
elements have browser default margins) has a lower vertical alignment than the right box (where the <p>
elements have had the margins removed and replaced with padding
) which sits perfectly in the center.
Why are the margins causing this issue, but the padding isn't?
*, *::before, *::after {
box-sizing: border-box;
-moz-box-sizing: border-box;
}
.container {
height: 100px;
border:1px solid #000;
margin-right:5%;
width:45%;
float:left;
}
.content {
position:relative;
top:50%;
-webkit-transform:translateY(-50%);
-ms-transform:translateY(-50%);
transform:translateY(-50%);
background-color:cyan;
}
.no_p_margin p {
margin:0;
padding:8px;
}
<div class="container">
<div class="content">
<p>Hello World</p>
<p>Hello World</p>
</div>
</div>
<div class="container">
<div class="content no_p_margin">
<p>Hello World</p>
<p>Hello World</p>
</div>
</div>