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

时间:2013-05-26 09:57:01

标签: html css

在下面的示例中,#logo绝对定位,我需要它在#header内水平居中。通常情况下,我会为相对定位的元素做margin:0 auto,但我被困在这里。有人能给我指路吗?

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

HTML

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

6 个答案:

答案 0 :(得分:283)

如果要对齐左侧属性中心。
同样的事情是顶部对齐,你可以使用margin-top :( div的宽度/ 2),概念与左属性相同。
将header元素设置为position:relative。是很重要的 试试这个:

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

DEMO

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

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

DEMO2

答案 1 :(得分:118)

您必须为left分配right0属性margin: auto值才能使徽标居中。

所以在这种情况下:

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

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

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

答案 2 :(得分:19)

在答案中错过了使用calc,这是一个更清洁的解决方案。

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

jsFiddle

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

在没有后备的情况下使用它可能还为时过早,但我想可能对未来的访问者来说会有所帮助。

答案 3 :(得分:7)

根据我的经验,最好的方法是right:0;left:0;margin:0 auto。这样,如果div很宽,那么left: 50%;不会妨碍你的div,从而导致增加负边距等。

DEMO http://jsfiddle.net/kevinPHPkevin/DeTJH/4/

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

答案 4 :(得分:4)

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

DEMO FIDDLE

代码 -

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

答案 5 :(得分:2)

它很容易,只需将它包装在一个相对的盒子里就像这样:

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

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