05 Mar 08 _ Position a div element absolute and align it top center using CSS

By Katy
in BlogTorials
I recently ran across this positioning problem. I was setting up a site where I needed a div layer (nav element) to go inside a layer with 100% width. I needed to position the div absolute, top and also align it in the middle of the page (see Pasta Technology for demo). CSS doesn’t always behave like you expect it would. But in the event you were wondering how to align your div top and center, here is the solution.
Set your container element’s position as absolute with top as 0px, if necessary. Next give it a position of left: 50%. Give the div an appropriate width for its contents. Then set it up with a margin-left as the negative value of half of the width. See my example:
#headerInside {
position: absolute;
top: 0px;
left: 50%;/*some magic to align the element in the center;
width: 1000px;
margin-left: -500px;/* half of the width */
}
You can also use the same principle if you want to align the element in the middle of the page vertically, by using top: 50%.










September 1st, 2008 at 4:05 pm
it work!!!
September 19th, 2008 at 7:17 am
Thanks girlfriend.
For some reason Dreamweaver gets moody. I can do everything the same EXACT way in two different test documents and when I switch to design view one would be centered differently than the other. And like I said, same exact code throughout the entirety of the document.
I like your site, hopefully all is well.
Check out my url if you’re interested at http://www.zafada.com
I’ve been using alot of my time lately learning javaScript..
September 19th, 2008 at 10:36 am
Saves an unnecessary wrapper div, thanks for the info.
October 1st, 2008 at 11:13 am
Wow! Saved me much hassle because the Zen Garden CSS project does not allow new Divs to be created.
Thank you!