Add to Technorati Favorites

adbits - tell the world

Center with Absolute Positioning

Votes: 587

I can't tell you how long this annoyed me, I had trouble figuring out how to position something absolutely, and keep it centered.  I'm not sure where I learned this, but I'll pass it on just the same.

I had to use this extensively at 121 Marketing Services Group, and as a side benefit, using absolute positioning can lead to less cross browser layout issues.

The search and the main nav div layers were positioned absolutely, as well as the logo, as it was flash, and had to be layered with z-ordering, but we'll get into that later. 

Setup the code

So lets get into some css code,to position the global nav I used this code.

#div_for_centering {

width:300;
height:200;

}

And we'd get this.

Center the div

#div_for_centering {

width:300;
height:200;
position:absolute;
left: 50%;

}

What's we've done here is, taken the left edge and moved that to the center of the page, hmm not really centered is it?

Finish it up

#div_for_centering {

width:300;
height:200;
position:absolute;
left: 50%;
margin-left:-150px;

}

To off set that we applied a negative margin, effectively offsetting the div to appear centered, go ahead, change the browser window size, it's staying true and center.

One word of caution however, Flash can have problem displaying in this "offset" area, the problem seems to only affect FireFox browsers however. 

 

Write a comment

  • Required fields are marked with *.

If you have trouble reading the code, click on the code itself to generate a new random code.
Security Code:
 
Mitch
Posts: 5
Comment
Center Image
Reply #5 on : Fri August 08, 2008, 14:23:20
Finally!! it works!
Don
Posts: 5
Comment
It doesn't work
Reply #4 on : Wed May 07, 2008, 15:39:05
It doesn't work. if you set the width to say 1000px and then minimize the broswer window to less then 1000px, the left side of the page starts disappearing
Tal
Posts: 5
Comment
That is totaly great !
Reply #3 on : Fri April 18, 2008, 17:57:27
I've been looking for a solution like this for hours!
I have a lot of content with absolute positioning which I want to center, and finally it works perfect !

THanks!
shawn himmelberger
Posts: 5
Comment
Hmm good question
Reply #2 on : Fri July 13, 2007, 13:30:52
I'll rip apart lightbox and see how they do it.
Andrew
Posts: 5
Comment
Eh, not so great
Reply #1 on : Fri July 13, 2007, 10:18:20
So what do you do with a variable width DIV?