中心对齐绝对定位的Div

Ste*_*eve 90 html css xhtml

div#thing {
  position: absolute;
  top: 0px;
  z-index: 2;
  margin: 0 auto;
}

<div id="thing">
   <p>text text text with no fixed size, variable font</p>
</div>
Run Code Online (Sandbox Code Playgroud)

股利是在顶部,但我不能居中<center>margin: 0 auto;

Jac*_*obE 148

如果您给出div固定宽度,可能会解决您的问题,如下所示:

div#thing {
    position: absolute;
    top: 0px;
    z-index: 2;
    width:400px;
    margin-left:-200px;
    left:50%;
}
Run Code Online (Sandbox Code Playgroud)

  • 这只是一种解决方法,http://stackoverflow.com/questions/1776915/how-to-center-absolute-element-in-div似乎是一个解决方案 (4认同)

小智 96

div#thing
{
    position: absolute;
    width:400px;
    right: 0;
    left: 0;
    margin: auto;
}
Run Code Online (Sandbox Code Playgroud)

  • 我同意这应该是正确的答案,一个-200px的余量尖叫对我来说是黑客. (4认同)
  • 这是如何运作的?你能否说明为什么你的答案有效? (3认同)

Mic*_*umo 32

我知道我迟到了,但我想我会在这里为需要水平放置绝对物品的人提供答案,当你不知道它的确切宽度时.

试试这个:

// Horizontal example.
div#thing {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}
Run Code Online (Sandbox Code Playgroud)

同样的技术也可以应用,因为当您可能需要垂直对齐时,只需调整属性如下:

// Vertical example.
div#thing {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
Run Code Online (Sandbox Code Playgroud)

  • 迈克尔,只是想让你知道,你没有迟到派对萌芽......对于那些不知道的人:转换:翻译(-50%, - 50%); 垂直和水平都以1线为中心 (3认同)
  • 绝对定位将从项目的左上角定位.使用translate会将其转换为相对于其大小的数量. (2认同)

Arm*_*min 5

要垂直和水平居中,请执行以下操作:

div#thing {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)