Click to return to home page
Richard Lowe Jr Home

Centering Things

For some reason which I cannot even begin to understand, the brainiacs that designed CSS neglected to include an easy and straightforward way to center non-textual elements. This is especially galling and noticeable when you attempt to center an image or an object such as a video. You can examine the entire CSS 1 and 2 specifications and you will not find an obvious way to do this.

It's as if the CSS designers either totally overlooked that people do occasionally want to center objects, or they decided it was not necessary.

XHTML STRICT does not allow the ALIGN attribute (it's been deprecated). So how the heck are you supposed to center an object?

The first, and most obvious, solution is to simply use the TEXT-ALIGN property of CSS. You might try this:

<img style="text-align:center" ...

Unfortunately, this does not work as you intend. The IMG tag simply ignores the property. If you want to center the image, you have to use a slightly different method.

<img style="display: block; margin-left: auto; margin-right: auto" ...

This will center your image as desired. This works as expected because it makes the margins to the right and left of the image of equal size.

You can make this simple by using a style sheet similar to the one below.

<style type="text/css">
Img.center{display:block; margin-left:auto; margin-right:auto}
</style>

And you use this in your XHTML code as follows.

<img class="center" ...

And that's all there is to it.


Unless otherwise noted, all photos and text is Copyright © Richard G Lowe, Jr.