I would like to show another cross-browser way which can solve this question using CSS3 calc()
.
We can use the calc()
function to control the margin-top
property of the child div when it's positioned absolute relative to the parent div.
The main advantage using calc()
is that the parent element height can be changed at anytime and the child div will always be aligned to the middle.
The margin-top
calculation is made dynamically (by css and not by a script and it's a very big advantage).
Check out this LIVE DEMO
<!DOCTYPE html>
<html>
<head>
<style>
#parent{
background-color:blue;
width: 500px;
height: 500px;
position:relative;
}
#child{
background-color:red;
width: 284px;
height: 250px;
position:absolute;
/* the middle of the parent(50%) minus half of the child (125px) will always
center vertically the child inside the parent */
margin-top: -moz-calc(50% - 125px);
/* WebKit */
margin-top: -webkit-calc(50% - 125px);
/* Opera */
margin-top: -o-calc(50% - 125px);
/* Standard */
margin-top: calc(50% - 125px);
}
</style>
</head>
<body>
<div id="parent">
<div id="child">
</div>
</div>
</body>
</html>
Output: