ubik ubik - 23 days ago 6
CSS Question

div does not get centered using margin: auto in IE9

I am trying to get a centered in the space that is left empty by a sidebar. This is how I'd like it to look like:

enter image description here

I actually managed to make this work OK for most browsers using

margin: auto
for the
div
in question, while setting
overflow: hidden
:

Fiddle here

CSS

#header {
height: 50px;
background: #224444;
color: #fff;
}

#container div {
padding: 1em;
}

#content {
max-width: 400px;
margin: auto;
background: #ddd;
height: 300px;
overflow: hidden;
}

#sidebar {
float: right;
width: 200px;
background: #aaa;
height: 300px;
}


HTML

<div id="container">
<div id="header">
PAGE HEADER
</div>
<div id="sidebar">
Sidebar
</div>
<div id="content">
Centered Content
(Works everywhere but on IE9)
</div>
</div>


However, it does not work with IE9. It is strange as IE8 works OK!

I am running out of ideas, so I thought that maybe someone knows what is going on? The trick seems to work perfectly everywhere else.

NOTE: Please note that the content
div
should be flexible as it is in the demo. As the available space decreases, it should change size and squeeze in.

Answer

Isolate the centering from the floating

This affects IE9/10.

It works fine if the floated element is removed, or if width is used instead of max-width. The presence of floated content, combined with the use of margin:auto and max-width instead of width, appears to be confusing IE9+.

To fix this, put the centered content in a wrapper div, so that the centering of the content can be separated from the floating of the sidebar. In other words, too much is happening layout-wise in a single div, more than IE9+ can handle. So split up the #content div into two separate divs.

#header {
    height: 50px;
    padding: 1em;
    background: #224444;
    color: #fff;
}

#content-wrapper {
    overflow: hidden;
}
#content {
    max-width: 400px;
    margin: auto;
    padding: 1em;
    background: #ddd;
    height: 300px;
}

#sidebar {
    float: right;
    width: 200px;
    padding: 1em;
    background: #aaa;
    height: 300px;
}
<div id="container">
    <div id="header">
        PAGE HEADER
    </div>
    <div id="sidebar">
        Sidebar
    </div>
    <div id="content-wrapper">
        <div id="content">
            Centered Content
        </div>
    </div>
</div>

This tested fine in IE7/8/9/10. On a side note, because a wrapper div was added, the padding: 1em; now has to be added to each element individually.