Webmaster Tutorials

Center an image using CSS

Center an image (absolutely!)

Posted on March 15th, 2011

Making an image (or some other block element for that matter) align in the center of its parent element can sometimes be quite a pain. One of the solutions to this problem is to use negative margins combined with absolute positioning to put the image exactly in the center. Absolute centered image markup This is …

Center an image (absolutely!)

Posted on March 15th, 2011

Making an image (or some other block element for that matter) align in the center of its parent element can sometimes be quite a pain. One of the solutions to this problem is to use negative margins combined with absolute positioning to put the image exactly in the center.

Absolute centered image markup

This is the markup we’re using.

Nothing difficult there, right?

Absolute centered image CSS

Now for the interesting part – the CSS.

div.myelement
{
	width: 500px;
	height: 500px;
}
div.myelement img
{
	position: absolute;
	left: 50%;
	top: 50%;
	width: 250px;
	height: 250px;
	margin-left: -125px;
	margin-top: -125px;
}

What we’ve done here is set the left and top margins of the image to be half of the image size. With the ‘top’ and ‘left’ absolute positioning doing the job of centering the top left corner of the image the margins give it that extra push to align it in the center.

...