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.