Sometimes the seemingly simplest tasks in front-end development can prove to be much more challenging than you’d think. Case in point, centering an object horizontally and vertically perfectly, dead center in a div or on a page. Without thinking too much, it’s easy to assume no big deal, the CSS is just align:center; and vertical-align:middle;, right? Nope. But we can achieve the desired results with just a few lines of CSS and some elementary school division; so let’s jump in.
Plug in your HTML
<img src=”http://i.imgur.com/7BfMx6R.png” width=”250″ height=”300″ />
For our uses, we’ll be centering an image but you can easily achieve the same results by replacing the image tag with text or whatever your needs are. The important thing here, in regards to our image, is making sure we note the dimensions.
Create a CSS centered class for our object
margin-left: -125px; /* width divided by 2 */
margin-top: -150px; /* height divided by 2 */
First step in our CSS is to define the width & height of our image; here we have a width of 250px and height of 300px.
We need to create the position: absolute declaration in order to activate the top & left properties with a value set to 50%. What this does is directs our object to be pushed down half the page from the Top edge and half way from the Left edge of the page.
If we stopped here, we’d be close but not quite centered. As mentioned above what we have thus far takes the top edge and pushes it down 50% and the left edge over 50%. So what’s happening is the top-left corner of our image is absolutely centered, but that’s not what we want. We’re looking for the dead center of our image to be centered. So we take the left edge and knock it back to the center by adding margin-left: -125px (the value is -125px is subtracting half of 250px). We’ll also need to knock it back up by half so we add in margin-top: -150px (again subtracting -150px from 300px gives us half aka the center of the image).
Check out the fancy diagram I made below to help explain this better.
And that’s it. If executed correctly, you should have your image lined up dead center of your page.