Centering Vertically and Horizontally

On some of my websites, such as my Catcher in the Rye fanlisting and If You Could See Me Now fanlisting, I am able to align the layout so that it is centred both horizontally and vertically. This tutorial will teach you how to do the same, but with a basic image. I’m going to be using the image below, a picture I took of James’s (my boyfriend) dog Keeks. I suggest using a simple image to begin with.

Keeks

Place the image in a new HTML document with the appropriate image code; make sure you include your regular HTML coding and call on your CSS file.

Now we need to wrap the contents to be centred in a <div>. I’ve chosen to call mine middle, so my basic code should look like this:

<div id="middle">
<img src="http://heartdrops.org/random/k.jpg" alt="Keeks" />
</div>

Now we need to tackle the CSS. Note that you may need to keep a calculator handy, unless you are good at doing basic division. ;)

The CSS for #middle is predictable to begin with:

#middle {
	 . . . 
}

Now we need to set this to position: absolute:

#middle {
	position: absolute;
}

The next step is to position the image at 50% of the width and height of the browser window.

#middle {
	position: absolute;
	left: 50%;
	top: 50%;
}

When you do this, you notice that it is positioned this way, because the top left corner of the image is actually the centre of the screen. What we need to do now is to pull the image to the left and up a bit, so that the centre of the screen is the centre of the image. This is where your calculator or terrific brain comes in.

You do need to know the dimensions of your image (or your div, whatever you are working with). The dimensions of my picture are 400px (width) and 301px (height).

Now to pull the image to the left and make it centered horizontally, we use a negative left margin. The negative margin value is not the full width of the image; rather, half the width.

Half of 400px is 200, so I need to use a negative left margin of 200px to make the image centre horizontally – margin-left: -200px:

#middle {
	position: absolute;
	left: 50%;
	margin-left: -200px;
	top: 50%;
}

See how that works? That’s why you need to be able to find half the width of your image or piece of content.

Now we do the same with the height, and this time we need to pull the image up, so we use a negative top margin. As you can see, I’ve chosen an image with an odd number on purpose. Half of 301 is 150.5, but I’m going to round that down and put 150 as the value to centre the image vertically – margin-top: -150px:

#middle {
	position: absolute;
	left: 50%;
	margin-left: -200px;
	top: 50%;
	margin-top: -150px;
}

You’re done! Try getting a friend to check in another resolution, or just resize your browser window or size of the page by zooming in or out.

You can see my working example if you’re stuck. If you found this tutorial useful please credit and link back to this website! :)