tags:

views:

401

answers:

2

OK so what would happen if I have 2 divs (one containing text, the other an image). The image always has a static width but the text varies. hence making its containing div variable.

I can make it work for all other browsers (except IE6 and IE7) by using CSS display:table. IE6 and 7 don't have that so I can't find a workable solution to center them all.

... so you know what I'm talking about...

.container{text-align:center; width:100%}

.container .centered{display:table; margin:0 auto}

    <div class="container">
        <div class="centered">
            <div id="text">varying length text</div>
            <div id="image">IMAGE</div>
        </div>
    </div>
A: 

Are you using quirksmode or standards compliant mode? In other words have you included a DOCTYPE declaration at the top of your html page?

You shouldn't need to use display:table just margin:auto should do the trick provided you are using a standards mode.

+1  A: 

Quite apart from the lack of IE support, setting display: table as you have without its children using display: table-row/table-cell results in undefined behaviour. It doesn't make sense to put block elements directly inside a table element and the browser might do anything at all.

What you are trying to do is get shrink-to-fit width behaviour without using float, which is a normal way of getting shrink-width but requires that the block in question goes to the left or right not centre. Probably a better way of saying that would be to use an inline-block:

.centered { text-align: center; }
.centered span { display: inline-block; border: dotted red 1px; }

<div class="centered">
    <span id="text">varying length text</span>
</div>
<div class="centered">
    <span id="image">IMAGE</span>
</div>

(You have to use a naturally-inline element like span to make it work under IE<8; div would fail. There is also -moz-inline-box if you need to target Firefox 2.)

bobince
Great answer! Inline-blocks are the key. I just used display:table without the child elements initially for all the recent browsers as it worked perfectly without the children - lazy I know.ONE THING, your solution didn't work perfectly as the .centered class still used display:block in IE6 as default (and inline-block doesn't work here)Simply add => .centered { text-align: center; display:inline }
Will
..err, it worked for me; setting it `display: inline` would make it no wider than the `span` inside it, which would break the centering as far as I can see (maybe there's something different in your context)
bobince