2

What I'm trying to do is have 3 columns of divs, aligned centrally on the page, such as:

Example (Says i'm not allowed to post an image)

I've tried various different suggestions from websites/blogs/other questions on here, but don't seem to be getting anywhere.

First I tried floating the divs left, then giving their parent div a width and margin:auto;

That didn't work, they just stayed left.

I noticed a lot of suggestions said to stop using float for this and use display:inline-block;

So I tried that and to an extent it works, e.g: fiddle

But as soon as I add any content to any of the divs, they stop being aligned and jump down the page.

What is the simplest way to achieve this (without using tables obviously)? As I'm sure it can't be as difficult as I'm making it.

Cheers.

CMR
  • 317
  • 4
  • 14
  • I tried your fiddle, and it works fine, even when I add some content to divs. In latest Firefox beta. Except that you have 1% margin-rights that visually shift them slightly to the left off center. – Matvey Andreyev Nov 05 '12 at 14:33

3 Answers3

0

To do that, you want to give the element you want aligned a width, with ‘auto’ left and right margins. This is the standards-compliant way that works everywhere except IE5.x.

<div style="width: 50%; margin: 0 auto;">Hello</div>

For this to work in IE6, you need to make sure Standards Mode is on by using a suitable DOCTYPE.

If you really need to support IE5/Quirks Mode, which these days you shouldn't really, it is possible to combine the two different approaches to centering:

<div style="text-align: center">
    <div style="width: 50%; margin: 0 auto; text-align: left">Hello</div>
</div>
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

There is a solution to center a float with unknown width: http://www.artlebedev.com/tools/technogrette/html/align-center/

Matvey Andreyev
  • 1,021
  • 10
  • 21
0

Adding vertical-align:top; to your .box will line the boxes up.

To address why adding text seems to fix the problem it is because

The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge.

from CSS2 Visual formatting model details.

Related question Why is this inline-block element pushed downward?

Community
  • 1
  • 1
andyb
  • 43,435
  • 12
  • 121
  • 150