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

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

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

我怎样才能做到这一点?


当前回答

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

其他回答

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

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

Flexbox可用于对绝对定位的div。

display: flex;
align-items: center;
justify-content: center;

.相对{宽度:275px;高度:200px;背景:皇家蓝;颜色:白色;边距:自动;位置:相对;}.绝对块{位置:绝对;高度:36px;背景:橙色;填充:0px 10px;底部:-5%;边框:1px实心黑色;}.居中文本{显示:柔性;对齐内容:中心;对齐项目:居中;盒子阴影:1px 2px 10px 2px rgba(0、0、0和0.3);}<div class=“relative center text”>相对块(Relative Block)绝对块</div></div>

只需使用一个新的div包装您的内容并使用display flex,然后使用align-items:center;并调整内容:中心;看看。。。

<div class="firstPageContainer">
  <div class="firstPageContainer__center"></div>
</div>
.firstPageContainer{
  display: flex;
  width: 1000px;
  height: 1000px;
  justify-content: center;
  align-items: center;
  background-color: #FF8527;
}

.firstPageContainer__center{
  position:absolute;
  width: 50px;
  height: 50px;
  background-color: #3A4147;
}

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/

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