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

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

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

我怎样才能做到这一点?


当前回答

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

这里还有更多的例子。

其他回答

这适用于垂直和水平:

#myContent{
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}

如果要使父对象成为元素中心,请设置父对象的相对位置:

#parentElement{
    position: relative
}

对于垂直居中对齐,请设置元素的高度。感谢劳尔。如果要使父对象成为元素中心,请将父对象的位置设置为相对位置

尽量不要使用CSS的阴暗面。避免使用负值作为边距。我知道有时候你会被迫做一些糟糕的事情,比如左边距:-450px,但你可能会做一些右边距:450px。这只是我的工作方式。

这个问题的公认解决方案不适用于我的情况。。。

我正在为一些图片做字幕,我用这个解决了这个问题:

top: 0;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;

display: flex;
align-items: center;

数字{位置:相对;宽度:325px;显示:块}图标题{位置:绝对;背景:#FFF;宽度:120px;填充:20px;-webkit框阴影:0 0 30px灰色;方框阴影:0 0 30px灰色;边界半径:3px;显示:块;顶部:0;左:0;右:0;左边距:自动;右边距:自动;显示:柔性;对齐项目:居中;}<图><img src=“https://picsum.photos/325/600"><figcaption>但也一样</figcaption></figure>

我使用了类似的解决方案:

#styleName {
    position: absolute;
    margin-left: -"X"px;
}

其中“X”是要显示的div宽度的一半。它适用于所有浏览器。

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/