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

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

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

我怎样才能做到这一点?


当前回答

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

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

其他回答

这是我想出的一个技巧,让DIV精确地浮在页面的中心。当然,它确实很难看,但它适用于所有浏览器。

点和虚线

<div style="border: 5 dashed red;position:fixed;top:0;bottom:0;left:0;right:0;padding:5">
    <table style="position:fixed;" width="100%" height="100%">
        <tr>
            <td style="width:50%"></td>
            <td style="text-align:center">
                <div style="width:200;border: 5 dashed green;padding:10">
                    Perfectly Centered Content
                </div>
            </td>
            <td style="width:50%"></td>
        </tr>
    </table>
</div>

清洁工

哇,那五年刚刚过去,不是吗?

<div style="position:fixed;top:0px;bottom:0px;left:0px;right:0px;padding:5px">
    <table style="position:fixed" width="100%" height="100%">
        <tr>
            <td style="width:50%"></td>
            <td style="text-align:center">
                <div style="padding:10px">
                    <img src="Happy.PM.png">
                    <h2>Stays in the Middle</h2>
                </div>
            </td>
            <td style="width:50%"></td>
        </tr>
    </table>
</div>

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

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

您还可以创建中间件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>

如果元素具有宽度和高度,则此解决方案有效

.包装器{宽度:300px;高度:200px;背景色:番茄;位置:相对;}.内容{宽度:100px;高度:100px;背景色:深蓝色;位置:绝对;顶部:0;右:0;底部:0;左:0;边距:自动;}<div class=“wrapper”><div class=“content”></div></div>

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