1

我在 IE7 中的定位和边距有问题。我有绝对位置和自动边距的 div。

position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
margin: auto;

这个 div 应该以它的相对位置父级为中心。但在 IE7 中,这是行不通的。这是工作代码的示例http://jsfiddle.net/3zwkA/

4

3 回答 3

3

如果您想将 div 绝对居中在它的父级中,您应该这样做:

.child {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 50px;
    height: 50px;
    margin-left:-25px;
    margin-top:-25px;
    border: 1px yellow solid;
}

查看更新的 jsfiddle

于 2013-02-08T16:03:10.933 回答
2

CSS 中的垂直居中是一种 PITA,尤其是当您还需要 IE7(甚至 IE6)支持时。有很多方法可以做到这一点,但每种方法都有一些缺点。您的方法对应于链接文章中的方法 4,并且已知在 IE < 8 中出现故障。

但是,对于具有固定宽度和高度的元素,一种更强大的方法(本文中的方法 2)包括将其定位在top: 50%; left: 50%顶部和左侧边距并减去宽度的一半。这适用于所有浏览器。在这里,有一个小提琴

于 2013-02-08T16:03:10.920 回答
2

我个人的“hack”是使用 left 和 top 放置元素,然后使用负边距正确移动它

position: absolute;
top: 50%;
left: 50%;
width: 50px;
height: 50px;
margin: -25px 0 0 -25px;  //move it left by half the width
于 2013-02-08T16:11:04.210 回答