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

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

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

我怎样才能做到这一点?


当前回答

您还可以创建中间件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 class="parent">
  <div class="child">
    <!-- content -->
  </div>
</div>

CSS:

.parent {
  position: relative;
}

.child {
  position: absolute;
  
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  margin: auto;
}

演示:http://jsbin.com/rexuk/2/

它在Google Chrome、Firefox和Internet Explorer 8中进行了测试。

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

宽度为900px。

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

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

我首选的定心方法:

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

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

一个JSFiddle在这里。

这对我有用:

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

您可以将图像放置在一个div中,添加一个div id,并让该div的CSS具有文本align:center:

HTML格式:

<div id="intro_img">

    <img src="???" alt="???">

</div>

CSS:

#intro_img {
    text-align: center;
}