我试图在侧边栏留空的空间中居中。这就是我希望它看起来像的样子:
我实际上设法让大多数浏览器都可以使用 margin: auto
为有问题的 div
,同时设置 overflow: hidden
:
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:auto
和 max-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/