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

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

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

我怎样才能做到这一点?


当前回答

#内容{margin:0自动;显示:表格;float:none;}<body><div><div id=“content”>我是内容</div></div></body>

其他回答

这适用于您希望在容器元素中心具有的绝对定位元素的任意未知宽度:

Demo

<div class="container">
  <div class="box">
    <img src="https://picsum.photos/200/300/?random" alt="">
  </div>
</div>

.container {
  position: relative;
  width: 100%;
}

.box {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

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/

这对我有用:

<div class="container><p>My text</p></div>

.container{
    position: absolute;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
}

可以使用calc()将纵横比为1的元素与位置绝对值居中

在下面的示例中,我使用了一个圆,因为它更容易解释和理解,但相同的概念可以应用于任何具有纵横比的形状:1表示宽度和高度相等。(关于纵横比)

:根目录{--直径:80px;}第二部分{位置:绝对;顶部:计算(50%-var(--直径)/2);右:计算(50%-var(--直径)/2);纵横比:1;width:var(--直径);边界半径:100%;背景:蓝色;}<div/>

解释

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

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