I have gone trough a lot of ways to horizontally and vertically center a DIV. Many of the code snippets had a Child DIV1 inside a Parent DIV2 to center the Child. They work perfect but I found a simpler way to center a single DIV trough CSS.
I am not sure if this is already known to all, but I experimented and came up with this simple CSS snippet.
Here is a visual representation of how this works:

Here is the CSS Snippet to be assigned to the DIV to be centered. The size of the DIV is 100 x 100 px ( same as the above example ).
/* CSS Document */
Here is another example with size 500 x 200 px.
/* CSS Document */
You can also find an online example here
Comments
That s great...thank you so much...and you can customize numbers than according to your website layout...
and if you want to apply it to your container DIV...just get rid of the TOP attributes...
thank you so much
Here is the solution for the div disappearing into top left corner of the browser's window:
http://stylizedweb.com/2008/02/01/vertical-align-div/
And here is the solution for variable (percentage) size div:
http://murphy.cz/victoria-s-vertical-centering/
Have a nice day :)
Here is code quite similar to dfadmin's that eliminates the problem of the "Center" layer/div resizing past the the vertical and horizontal page view of the "Center" layer's dimensions. It works cross-browser and prints perfectly -
'Wrapper' position is 'relative' - 100% height and width layer aspects:
html, body, #Wrapper, #Center {
height: 100%;
min-height: 400px;
width: 100%;
min-width:500px;
margin: 0;
padding: 0;
border: none;
}
#Center {
position: absolute;
left: 50%;
top: 50%;
width: 500px;
height: 400px;
margin-top: -200px;
margin-left: -250px;
border: 1px solid #333;
background-color: #C0C0C0;
}
This is by far the easiest and simplest way to horizontally and vertically center a DIV. Thanks a million "dfadmin"
-Kurt
Yes .. it is a good method, however .. with resizing the browser window it won't work.
You need what is called a SHIM div for this .. that pushes it back. However I can't find the code anymore.
this works great ... except when the user wants a print out - the site is pushed up and left off the page ... or am i missing smthg really obvious here?
you are my hero
The only downside to this is that it can't be used when the height of the object to be centered is unknown. That's why the other solutions are so much more complicated..
Hey, this works great!
I can't imagine a simpler solution. I feel stupid for not thinking of it myself :-)
Only problem is if u use it for a whole page and the users window is too small. When the scroll bars come up it cuts off the top of the page. (Try it out on the demo)
Im having real trouble sorting this out, I cant believe such a simple thing could be sooooo much trouble.
Ideas any one?
Post new comment