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, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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.

Anonymous 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..