{"authorId":1,"title":{"title":{}},"slug":"centering-absolutely-positioned-items","postDate":1183858764,"expiryDate":null,"enabled":1,"fields":{"2":"<p>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.<\/p>\n\n<p>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&rsquo;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.<\/p>\n\n<p>So I went in and added <code>margin: 0 auto<\/code> like I normally would to center anything, but then I realized since it is absolutely positioned, it would&rsquo;t work like that.<\/p>\n\n<!--more-->\n\n<h2>How to Center the Absolute Positioned Item<\/h2>\n\n<p>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.<\/p>\n\n<h3>Example<\/h3>\n\n<p>Here is the CSS that I started with:<\/p>\n\n<div class=\"codeblock\"><code>\ndiv#centered&nbsp;&#123;<br \/>&nbsp;height:&nbsp;300px;<br \/>&nbsp;left:&nbsp;50%;<br \/>&nbsp;position:&nbsp;absolute;<br \/>&nbsp;top:&nbsp;20px;<br \/>&nbsp;width:&nbsp;500px;<br \/>&#125;&nbsp;\n\n<\/code><\/div>\n\n<p>Ok, so now we&rsquo;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 <strong>250px<\/strong>.<\/p>\n\n<p>So if we set a negative left margin of <strong>-250px<\/strong>, we end up with the following CSS:<\/p>\n\n<div class=\"codeblock\"><code>\ndiv#centered&nbsp;&#123;<br \/>&nbsp;height:&nbsp;300px;<br \/>&nbsp;left:&nbsp;50%;<br \/>&nbsp;margin-left:&nbsp;-250px;<br \/>&nbsp;position:&nbsp;absolute;<br \/>&nbsp;top:&nbsp;20px;<br \/>&nbsp;width:&nbsp;500px;<br \/>&#125;&nbsp;\n\n<\/code><\/div>\n\n\n<p>You can see that <a href=\"http:\/\/trevordavis.net\/play\/absolutePositionCenter\/\">the absolutely positioned item is now centered<\/a>.<\/p>\n\n<h2>In Case You Didn&rsquo;t Notice&hellip;<\/h2>\n\n<p>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.<\/p>","4":{"website":{}}}}