CSS Centering Images

Posted on 6 August 2010 | by Ryan Battles

Okay, this is elementary CSS stuff, but I always forget exactly how to do this.

How do I properly center an image in CSS?

There are several answers to this.  Before I begin, it is important to remember that images are displayed inline by default.  This means that they appear “in line” with text, and do not take up a whole block width the way a heading or a paragraph would.  Because of this, setting a margin of “auto” won’t work on images by default, because this only applies to block elements.  Also, if you give the image itself a style of text-align:center, this won’t work either.  What you are declaring here is that you want everything within the image tag to be centered.  The image tag only takes up the space that the image does, so centering is a moot point.

Solutions:

  1. Give a style to the surrounding container (the paragraph, div, etc.) of text-align:center.  The image will be centered, as well as any text that is also within that block.
  2. Give a style to the image to be display:block, and then give it a margin-left and margin-right of “auto”.

Bonus:

While not that popular, it is also possible to center images vertically.  Try this:

DIV.container {
    min
-height10em;
    
displaytable-cell;
    
vertical-alignmiddle;

Any text or image within will be vertically aligned.

Tags: web development, quicktip, css

Related Posts

Comments (1)

Spur Shelving
Sep. 30, 2010

I often forget this too and using CSS is certainly better than the HTML center tags. Thanks!

Join the Discussion


Commenting is not available in this weblog entry.