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

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

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

我怎样才能做到这一点?


当前回答

响应式解决方案

假设div中的元素是另一个div。。。

此解决方案运行良好:

<div class="container">
  <div class="center"></div>
</div>

容器可以是任何大小(必须是相对位置):

.container {
    position: relative; /* Important */
    width: 200px; /* Any width */
    height: 200px; /* Any height */
    background: red;
}

元素(div)也可以是任何大小(必须小于容器):

.center {
    position: absolute; /* Important */
    top: 50%; /* Position Y halfway in */
    left: 50%; /* Position X halfway in */
    transform: translate(-50%,-50%); /* Move it halfway back(x,y) */
    width: 100px; /* Any width */
    height: 100px; /* Any height */
    background: blue;
}

结果将是这样的。运行代码段:

.容器{位置:相对;宽度:200px;高度:200px;背景:红色;}.中心{位置:绝对;顶部:50%;左:50%;转换:转换(-50%,-50%);宽度:100px;高度:100px;背景:蓝色;}<div class=“container”><div class=“center”></div></div>

我觉得这很有帮助。

其他回答

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

如果需要水平和垂直居中:

left: 50%;
top: 50%;
transform: translate(-50%, -50%);

<div style='position:绝对;左:50%;顶部:50%;转换:转换(-50%,-50%)'>此文本居中。</div>

这将使div中的所有对象居中,位置类型为static或relative。

您还可以创建中间件div#centered框,以绝对值、左财产和右财产居中,不带width属性,然后将主内容div设置为其具有display:inline-block框的子项,并使用为其中间件父框设置的text-align:center将其居中

#集装箱{位置:相对;宽度:300px;高度:300px;边框:实心1px蓝色;颜色:#DDDDD;}#居中{位置:绝对;文本对齐:居中;边距:自动;顶部:20px;左:0;右:0;边框:1px红色虚线;填充:10px 0px;}#居中>div{边框:实心1px红色;显示:内联块;颜色:黑色;}<div id=“container”>你好世界你好世界你好世界你好世界你好世界你好世界你好世界你好世界你好世界你好世界你好世界你好世界你好世界你好世界你好世界你好世界<div id=“center”><div>你好世界<br/>我不知道我的宽度<br/>但我还是绝对的!</div></div></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/