Position: Absolute; (Centered)

It’s pretty easy to center a relatively positioned div:

#div { position: relative; margin: 0 auto; }

However, sometimes centering a div that has an absolute position can be a little tricky. Here’s a workaround that I’ve been using that seems to get the job done. Say you have a logo that you want to center in your header and it has a position that is absolute, sort of like the following example:

<div id="body">
<div id="header">
<div id="logo"> logo </div>
<div id="maincontent"> main content</div>
<div id="footer"> footer </div>

Basically, what you can do is give the div #logo a value of left: 50%. The first thing you’ll notice is that the div doesn’t appear to be perfectly centered. Well, that’s because it’s not. It’s simply starting at the halfway point in your screen. To center the div you’ll need to make sure there is a clarified width. Then, take the width and divide it by 2 (round to even number). The result of half your width is what you will set your margin-left to in a negative value. Here’s a quick example:

#logo { position: absolute; width: 108px; left: 50%; margin-left: -54px; }

And that should just about do it. If you have an alternate, or better way of accomplishing absolute centered, leave a comment!

Tags: , ,

Trackback from your site.

Nick Winters

Nick Winters is the Web Marketing & Graphic Designer for Wenatchee Valley College and owner of Pixel to Press, LLC. He enjoys many outdoor activities, such as: Skiing, Snowboarding, Mountain Biking, Wakeboarding, and Wakesurfing. Never not working, never not having fun.

Leave a comment