Re: Center DIV

Afternoon / 2003-07-03 17:15:
> On Thursday, Jul 3, 2003, at 15:18 Europe/London, Jonas Galvez 
> wrote:
> 
>> Hi, this is my first post on this list. Does anybody know an 
>> efficient way to place a <div> on the center of the page? I've 
>> tried everything. I read an article over @ mrclay.org (url 
>> below) and the technique he teaches seems to be the perfect 
>> approach (in terms of CSS), but unfortunately, it doesn't work 
>> in IE.
>> 
>> http://mrclay.org/web_design/centered_image/
>> 
>> The *solution* I found was to position the image at 50% of the 
>> page and then compensate with a negative margin (with half of 
>> the size of the image). For example:

The problem with this method is, as somebody already mentioned, that 
it breaks if the containing element is narrower than the content 
you're trying to "center". As a result, compliant browsers overflow 
the content towards left. And, for example, Mozilla doesn't have a 
method to display content that's positioned upwards or towards left 
from top left corner of the viewport and I'm not sure if that's a 
bug (it sure  is a accessibility problem, but if it's because of 
browser or broken page is up to a discussion).

See also: <URL:http://bugzilla.mozilla.org/show_bug.cgi?id=6976>

> No, there really isn't one.
> 
> I recommend writing non-standard HTML such as that required to
> create a 100% table. Just leave out the DOCTYPE. Who cares if it
> validates. The view of people who wish to center block level
> objects and the view of the W3C CSS working group will not be
> harmonised for some time yet.

Yes, if you *need to have perfect rendering* in MSIE, you have to 
use un-meaningful markup and I'm doing that too for some webapps I'm 
writing. However, it's not because W3C CSS group didn't gave us 
tools required to do centering with CSS only, but it's MS not 
following the specs the group has provided.

The "right" method:

markup:
<div class="container"><img alt="ALTERNATE text"/></div>

with style:
.container {
   width: whatever-you-like;
   height: whatever-you-like;
   display: table-cell;
   vertical-align: center;
}
.container > img
{
   display: block;
   margin: auto;
}

...but as I said, MSIE doesn't support CSS2 enough for this to be 
used. So *if you care about a single broken browser* you cannot use 
the CSS method.

( I'd rather have vertical-align property to apply to all block 
level elements instead of just to table cells or margin: auto to 
center vertically in addition to horizontal centering. Messing with 
4 properties (display for both elements, vertical align for 
containing block and margin for contained element) just to center 
both vertically and horizontally is too much. )

-- 
Mikko

Received on Friday, 4 July 2003 08:15:07 UTC