如何在一个100% 宽度的 div 中水平居中一个绝对定位元素?

在下面的例子中,#logo是绝对定位的,我需要它是水平居中的 #header。通常,我会做一个 margin:0 auto相对定位的元素,但我卡在这里。有人能给我带路吗?

小提琴: http://jsfiddle.net/DeTJH/

超文本标示语言

<div id="header">
<div id="logo"></div>
</div>

CSS

#header {
background:black;
height:50px;
width:100%;
}


#logo {
background:red;
height:50px;
position:absolute;
width:50px
}
193067 次浏览

如果要在左侧属性上对中心。
对于 top 对齐也是一样的,你可以使用 edge-top: (width/2 of your div) ,这个概念和 left 属性是一样的。
将标题元素设置为 position: relant 非常重要。
试试这个:

#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left:50%;
margin-left:-25px;
}

演示

如果你不想使用计算,你可以这样做:

#logo {
background:red;
width:50px;
height:50px;
position:absolute;
left: 0;
right: 0;
margin: 0 auto;
}

DEMO2

您必须为 margin: auto分配 leftright属性 0的值,以便使标志居中。

因此,在这种情况下:

#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}

您可能还需要为 #header设置 position: relative

这是因为,将 leftright设置为零将水平拉伸绝对定位的元素。现在,当 margin设置为 auto时,奇迹发生了。margin占用了所有额外的空间(同样在每一边) ,将内容留给它指定的 width。这导致内容成为中心对齐。

根据我的经验,最好的方法是 right:0;left:0;margin:0 auto。这样,如果 div 是宽的,那么你就不会受到 left: 50%;的阻碍,因为 left: 50%;会抵消掉你的 div,从而增加负的边距等等。

演示 http://jsfiddle.net/kevinPHPkevin/DeTJH/4/

#logo {
background:red;
height:50px;
position:absolute;
width:50px;
margin:0 auto;
right:0;
left:0;
}

以下是将 div 居中为位置绝对值的最佳实践方法

小提琴演奏

密码

#header {
background:black;
height:90px;
width:100%;
position:relative; // you forgot this, this is very important
}


#logo {
background:red;
height:50px;
position:absolute;
width:50px;
margin: auto; // margin auto works just you need to put top left bottom right as 0
top:0;
bottom:0;
left:0;
right:0;
}

在答案中缺少 calc的使用,这是一个比较干净的解决方案。

#logo {
position: absolute;
left: calc(50% - 25px);
height: 50px;
width: 50px;
background: red;
}

jsFiddle

适用于大多数现代浏览器: http://caniuse.com/calc

也许现在就使用它还为时过早,但我想也许对未来的访客会有帮助。

很简单,只要把它包在一个相对的盒子里,就像这样:

<div class="relative">
<div class="absolute">LOGO</div>
</div>

相对框有一个边距: 0自动; 重要的是,宽度..。