Absolute Center Images With CSS
Join the DZone community and get the full member experience.
Join For FreeHere is a technique about how you can absolute center position an element on the horizontal and vertical in CSS.
Center Images Horizontally
To center something on the horizontal in CSS it's quite easy all you need to do is set the width on the element and apply an auto margin-left and margin-right on to the image. The browser will work out the exact margin on both the right and left side of the image. This will position the image in the center of the parent element just by using the width and the margin properties.
<img src="example.html" alt="Center Images" />
img { width:250px; margin: 0 auto; }
Center Images On Horizontal and Vertical
Setting the image to be center on the horizontal is easy you just need to set an auto on the left and right margin. But to set the image on the vertical and on the horizontal you need to set the margin on the top and left of the element.
The following technique is something you can use to display a pop-up window to show an image gallery in the center of the screen.
This example will center the image with a width of 250px, first to set the image to be absolute positioned and set the top and left property to be 50%. This will position the image in the middle of screen, but the image won't be exactly center.
img { height: 250px; left: 50%; position: absolute; top: 50%; width: 250px; }
The top left corner of the image will be the exact center of the screen, to move this point to the center of the image we need to move the image half it's width and half it's height. To move the image on half it's width and half it's height you need to add a margin-top which is negative half the height of the image and a margin-left which is negative half the width of the image.
img { height: 250px; left: 50%; margin-top: -125px; margin-left: -125px; position: absolute; top: 50%; width: 250px; }
Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments