a:2:{i:0;a:1:{s:4:"data";a:1:{s:7:"entries";a:1:{i:0;a:7:{s:2:"id";s:3:"276";s:5:"title";s:37:"Centering Absolutely Positioned Items";s:11:"displayDate";s:10:"07.07.2007";s:13:"attributeDate";s:10:"2007-07-07";s:4:"body";s:2218:"
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.
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.
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.
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.
";s:13:"numberOfLikes";N;s:10:"bodyBlocks";a:0:{}}}}}i:1;O:25:"yii\caching\TagDependency":3:{s:4:"tags";a:4:{i:0;s:7:"element";i:1;s:29:"element::craft\elements\Entry";i:2;s:40:"element::craft\elements\Entry::section:4";i:3;s:7:"graphql";}s:4:"data";a:4:{s:40:"CraftCMSce35088bdfe0816226cd17fd051a4803";s:21:"0.70573500 1736501960";s:40:"CraftCMS2743a789e8993267a348eee1ee7e4450";s:21:"0.67537500 1713205687";s:40:"CraftCMS2ac34726f299f7e18e449d8e536c67f8";s:21:"0.84529700 1741778847";s:40:"CraftCMS3817d4a648fcfac939af46605323feb0";s:21:"0.36746500 1735923287";}s:8:"reusable";b:0;}}