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, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

3 Responses to "Centering a DIV inside a DIV – Both Horizontal and Vertical"
  1. mstekl said...
    July 14, 2009 at 7:57 PM

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

  2. shifteleven said...
    July 15, 2009 at 4:59 AM

    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?

  3. Suprotim Agarwal said...
    July 16, 2009 at 4:59 AM

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

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions