Centering Images as IMG tag or Background Image

This is just a quick hack on central positioning of images within your website. I allways forget how to do this so I decided to write it on my blog as a quick reference.

Positioning Images via background css property

Default background-position is 0 0 which means left top, so if you need it central just make it background-position center top or 50% 0. This will position the pivot point of the image in the center and position that point in the center of your container. Beware: positioning the background image with left: 50% will set pivot point to begining  of the  image.

background-image: url(whatever.jpg);
background-position: 50% 0;

See the Pen The Difference Between background-position and left by Chris Coyier (@chriscoyier) on CodePen.


Positioning image with img Tag

If you indeed need to position the image it self in the center there is a nifty little CSS3 hack for that.  Simply set the img to left: 50%; and translate the image pivotal point manualy to the middle of the image via transform: translateX(-50%); Note: the container has to be position: relative;

<img src=”whatever.jpg”/>

img { position: relative; left: 50%; transform: translateX(-50%); }



Leave a Reply

Your email address will not be published. Required fields are marked *