wickedways.org :: web standards all around

Am a newbie so apologies if this is obvious. I have a layer in which the text is aligned left. Using CSS how do I get an image in the same layer to be centred?

— Graham from csscreator.com

Approach one

This first approach breaks the image from the surrounding text and centers it between the margins. It’s a popular treatment in printed media because it’s simple to do and it draws attention to the image without interrupting the edges of the text. (A floated image breaks the flow of the text at the margin, interrupting the pace of the eye as it pores over the page.)

First, make the image a block element by using display: block; to separate the image from the text that surrounds it. Then, use margin-left: auto; margin-right: auto; to center it.

Example 1

Mauris cursus neque id libero. Cras aliquet ligula id urna. Aenean elit. Ut et felis vitae lectus rhoncus volutpat.

A dog in a room with a plan

Donec turpis ipsum, commodo nec, tincidunt fermentum, venenatis vitae, elit. Aenean tortor ipsum, tempus et, cursus sed, sodales ac, neque.

The HTML

<p>Mauris cursus neque …<p>
<img src="/images/adog.jpg" alt="A dog in a room with a plan" />
<p>Donec turpis ipsum, …</p>

The CSS

#example1 img {
display: block;
margin-left: auto;
margin-right: auto;
}

Approach two

I think that approach one is a clean, simple solution that probably accomplishes what you were looking for, but margin-left: auto; margin-right: auto; doesn’t center images in older browsers. You can use a container div to make sure IE5.x gets it right while achieving the same effect in more compliant browsers.

Example 2

Mauris cursus neque id libero. Cras aliquet ligula id urna. Aenean elit. Ut et felis vitae lectus rhoncus volutpat.

A dog in a room with a plan

Donec turpis ipsum, commodo nec, tincidunt fermentum, venenatis vitae, elit. Aenean tortor ipsum, tempus et, cursus sed, sodales ac, neque.

The HTML

<p>Mauris cursus neque …</p>
<div class="frontandcenter"><img src="/images/adog.jpg" alt="A dog in a room with a plan" /></div>
<p>Donec turpis ipsum, …</p>

The CSS

div.frontandcenter {
text-align: center;
}