html - div 没有使用边距 : auto in IE9 居中

标签 html css internet-explorer internet-explorer-9

我试图在侧边栏留空的空间中居中。这就是我希望它看起来像的样子:

enter image description here

我实际上设法让大多数浏览器都可以使用 margin: auto 为有问题的 div,同时设置 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>

但是,它不适用于 IE9。很奇怪,IE8 可以正常运行!

我的想法已经用完了,所以我想也许有人知道发生了什么事?这个技巧似乎在其他任何地方都适用。

注意:请注意内容div 应该是灵活的,因为它在演示中。随着可用空间的减少,它应该改变大小并挤进去。

最佳答案

将居中与 float 隔离

这会影响 IE9/10。

如果 float 元素被移除,或者如果使用 width 而不是 max-width,它工作正常。 float 内容的存在,结合 margin:automax-width 而不是 width 的使用,似乎让 IE9+ 感到困惑。

要解决此问题,请将居中的内容放在包装器 div 中,以便内容的居中可以与侧边栏的 float 分开。换句话说,在单个 div 中发生了太多的布局方面的事情,超出了 IE9+ 的处理能力。所以将 #content div 分成两个单独的 div。

#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>

这在 IE7/8/9/10 中测试良好。附带说明一下,因为添加了包装器 div,所以现在必须将 padding: 1em; 单独添加到每个元素。

关于html - div 没有使用边距 : auto in IE9 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16217546/

相关文章:

html - CSS3 变换 : Chrome Solution

jquery - Django 使用 Jquery 来 POST 数据

javascript - 在同一上下文中具有其他 JS 函数的 Jcrop 插件

CSS 属性选择器、多个类、应用于一个类定义的通配符可能吗?

android - ThemeRoller 不适用于设备

html - 绝对定位图像左下角页面 - 它只是行不通

css - 如何将背景颜色设置为侧边栏位置以跨越整个页面长度和屏幕右侧的边缘

html - 如何使IE中网页上的文本框与Chrome中的文本框相同

java - 在 IE 中启用 pdf 缓存

css - IE 中不需要的 (img) 侧边距