Page is a not externally linkable
- Code, Content, and Presentation
-- CSS
---- How to center images


Hagstrom - 10:11 am on Feb 8, 2004 (gmt 0)


"One of the goals of CSS is to provide an alternative to HTML extensions."

For more time than I care to admit, I have struggled with finding out how to center images with CSS. Unfortunately the HTML specs [w3.org] only tell you how to center text with text-align:center.

This solution works with Internet Explorer - leading people (like me) to believe that this is the right way to do it. But it's not.

  1. The right way to center objects is to specify margin-left:auto and margin-right:auto.
    This explained in the CSS specs [w3.org].

  2. This won't work for some objects - like images!

    The reason is that images are not considered blocks even though they are quadrangular!

    So you have to specify display:block.

  3. Unfortunately this doesn't work with older versions of Internet Explorer (I have tried IE4).
    So you have to add
    text-align:center.

    This is not a problem for images, but if you use text-align:center to center a text-object your text will also be centered, so you have to have to nest two objects (e.g. a <p> within a <div> )

So the result is:

<style>
img.mycenter {margin-left:auto; margin-right:auto; display:block; text-align:center;}
</style>

<img class="mycenter" src="....." height="...." width="....">


Thread source:: http://www.webmasterworld.com/css/2857.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com