No public Twitter messages.

Centering Absolutely Positioned Items

At work the other day, I was working on the homepage of a small save the date site. We had so many beautiful images to use, so our designer decided to limit the text that is on the homepage. So the container is absolutely positioned with a height of 100% in order to fill the viewport.

The client wrote back right before we were ready to launch and said that they noticed a large white margin on the right hand side. We had to explain to them that since the design was left aligned and the picture can’t go on forever, there has to be an end to the design. We decided to center the design in order to make it look better.

So I went in and added margin: 0 auto like I normally would to center anything, but then I realized since it is absolutely positioned, it would’t work like that.

How to Center the Absolute Positioned Item

After doing some thinking, I thought about positioning the item from the left edge a certain percent. So I thought if I moved it over 50% and then shifted it back to the right, then it should work.

Example

Here is the CSS that I started with:

div#centered {
	height: 300px;
	left: 50%;
	position: absolute;
	top: 20px;
	width: 500px;
}

Ok, so now we’ve got it shifted over 50% from the left hand side, and in order to get it back to the center, you need to take half of the width of the item, in this case 250px.

So if we set a negative left margin of -250px, we end up with the following CSS:

div#centered {
	height: 300px;
	left: 50%;
	margin-left: -250px;
	position: absolute;
	top: 20px;
	width: 500px;
}

You can see that the absolutely positioned item is now centered.

In Case You Didn’t Notice…

I alphabetize my CSS properties. It makes everything so much easier to maintain. Once you actually start to think about it, it pretty much comes naturally too. Give it a shot.

Share This:
  • del.icio.us
  • Digg
  • Twitter
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • NewsVine
  • Technorati
  • Reddit
  • LinkedIn

RSS feed of comments for this entry

Speak Your Mind

* Denotes Required Field

  1. To post code snippets, use <pre><code>YOUR CODE HERE</code></pre>
Me, Trevor Davis. My blue steel face…

Hi, I’m Trevor Davis

I’m a 25 year old Front-End Developer living in Arlington, VA. I work full-time at Viget Labs and freelance on the side.

I specialize in CSS, HTML, jQuery, WordPress & ExpressionEngine. See more of my work, and then hire me.

Recent Work

  • 4th District IBEW Health Fund
  • Employers Council on Flexible Compensation
  • Monica Davis
  • The National Christmas Tree
  • Matrix Group International
  • The MatriX Files
  • Wireless Career
  • George Washington Wired
  • Direct Selling 411
  • Makeup Bizz
  • InstallNET
  • National Park Foundation
See More of My Work

Asides