中心对齐绝对定位的Div

时间:2008-10-31 08:10:34

标签: 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>

div位于顶部,但我无法将其与<center>margin: 0 auto对齐;

8 个答案:

答案 0 :(得分:147)

如果您为div提供固定宽度,则问题可能会解决,如下所示:

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

答案 1 :(得分:93)

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

答案 2 :(得分:1)

.contentBlock {
    width: {define width}
    width: 400px;
    position: absolute;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
 
}

答案 3 :(得分:0)

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

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

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

答案 4 :(得分:0)

I was having the same issue, and my limitation was that i cannot have a predefined width. If your element does not have a fixed width, then try this

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

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

then modify your html to look like this

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

答案 5 :(得分:0)

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

div#thing {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

答案 6 :(得分:0)

或者您可以使用相对单位,例如

#thing {
    position: absolute;
    width: 50vw;
    right: 25vw;
}

答案 7 :(得分:-22)

是:

div#thing { text-align:center; }