我想在窗口的中心放置一个div(with position:absolute;)元素。但我在这样做时遇到了问题,因为宽度未知。

我尝试了以下CSS代码,但它需要调整,因为宽度是响应的。

.center {
  left: 50%;
  bottom: 5px;
}

我怎样才能做到这一点?


当前回答

由于我不想更改容器/包装器元素的样式,所以这些解决方案都不适合我。这段代码对我有用:

position: absolute;
left: 50%;
margin-left: -50px;
top: 50%;
margin-top: -50px;

其他回答

HTML格式:

<div class="wrapper">
    <div class="inner">
        content
    </div>
</div>

CSS:

.wrapper {
    position: relative;

    width: 200px;
    height: 200px;

    background: #ddd;
}

.inner {
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
    margin: auto;

    width: 100px;
    height: 100px;

    background: #ccc;
}

这里还有更多的例子。

这对我有用:

#内容{位置:绝对;左:0;右:0;左边距:自动;右边距:自动;宽度:100px;/*需要特定的值才能工作*/}<body><div><div id=“content”>我是内容</div></div></body>

Sass/Compass版本的先前响应解决方案:

#content {
  position: absolute;
  left: 50%;
  top: 50%;
  @include vendor(transform, translate(-50%, -50%));
}

在寻找解决方案时,我得到了前面的答案,可以将内容以Matthias Weiler的答案为中心,但使用文本对齐:

#content{
  position: absolute;
  left: 0;
  right: 0;
  text-align: center;
}

它与谷歌Chrome和Firefox配合使用。

HTML

<div id='parent'>
  <div id='centered-child'></div>
</div>

CSS

#parent {
  position: relative;
}
#centered-child {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto auto;
}

http://jsfiddle.net/f51rptfy/