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

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

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

我怎样才能做到这一点?


当前回答

我只是想补充一句,如果有人想用一个div标记来完成,那么这里是解决方法:

宽度为900px。

#styleName {
    position: absolute;
    left: 50%;
    width: 900px;
    margin-left: -450px;
}

在这种情况下,应该事先知道宽度。

其他回答

这对我有用:

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

我首选的定心方法:

position: absolute;
margin: auto;
width: x%

绝对块元素定位保证金自动左/右、上/下相同

一个JSFiddle在这里。

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

这里还有更多的例子。

响应式解决方案

假设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>

我觉得这很有帮助。

这对我有用:

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

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