Centering a DIV inside a DIV – Both Horizontal and Vertical

I was recently facing this issue of centering a DIV both horizontally and vertically inside another DIV. Here’s the solution I came up with. I have tested the solution in IE7, Mozilla 3 and Chrome 2

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">

<
head>
<
meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<
title>Foo foo</title>
<
style type="text/css">
div
{
border:thin gray solid;
}

#parentDiv {
position:relative;
height:500px;
width:100%;
}
#childDiv {
position:absolute;
top:50%;
height:250px;
width: 50%;
margin-top:-125px;
margin-left:250px;

}
</style>
</
head>

<
body>
<
div id="parentDiv">
<
div id="childDiv">Your Text Goes Here</div>
</
div>
</
body>

</
html>
OUTPUT

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

3 comments:

mstekl said...

or you can use
margin:auto;
in the cliddiv, instead of hardcoding the margin-left value.

shifteleven said...

Nice. One thing to note, you explicitly set the height in the middle div. How would you handle this if you had an unknown height?

Suprotim Agarwal said...

Did you try setting the Bottom property for the inner div? That should do the trick. I will have to try that to confirm..