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>

div位于顶部,但我不能用<center>margin: 0 auto;

来居中
有帮助吗?

解决方案

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

div#thing {
    position: absolute;
    top: 0px;
    z-index: 2;
    width:400px;
    margin-left:-200px;
    left:50%;
}

其他提示

div#thing
{
    position: absolute;
    width:400px;
    right: 0;
    left: 0;
    margin: auto;
}

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

试试这个:

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

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

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

如果您需要具有相对宽度(以百分比表示),则可以将div包装在绝对定位的位置:

div#wrapper {
    position: absolute;
    width: 100%;
    text-align: center;
}

请记住,为了绝对定位元素,必须相对定位父元素。

我遇到了同样的问题,我的限制是我不能有预定义的宽度。如果你的元素没有固定宽度,那么试试这个

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

div#thing-body
{
  text-align:center;
}

然后修改你的html看起来像这样

<div id="thing">
 <div id="thing-child">
  <p>text text text with no fixed size, variable font</p>
 </div>
</div>

是:

div#thing { text-align:center; }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top