垂直对齐-z索引



我正在尝试垂直对齐一个模态框。但是margin-top:50%并没有像我预期的那样工作。基本上我想要一个以另一个正方形为中心的正方形。

<style type="text/css">
#modal {
    width: 300px;
    height: 300px;
    z-index: 100;
    background-color: red;
    margin: 0 auto;
    position:relative;
    margin-top:50%; //problem here
}
#content {
    position: absolute;
    width:950px;
    height: 950px;
    margin: 0 auto;
    background-color: green;
}
#replace {
 width:950px;
 height:500px;   
}

</style>
<div id="replace">
<div id = "content"></div>
<div id="modal"></div>
</div>

感谢

演示

您需要为#modal 使用top:325px;而不是保证金

如果在contentdiv中包含modal不会太麻烦,您可能需要尝试以下HTML:

<div id = "content">
    <div id="modal"></div>
</div>

使用此CSS:

#modal {
    width: 300px;
    height: 300px;
    background-color: red;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -150px;
    margin-top: -150px;
}
#content {
    position: absolute;
    width: 550px;
    height: 550px;
    background-color: green;
}

演示

基本上,您完全将modaldiv定位在contentdiv内,并告诉它从顶部的50%和左侧的50%开始。这将使modal的左上角居中,但不是整个div。为了将div作为一个整体居中,您必须添加一个负边距,将其向上和向左移动。负裕量是modal分区高度/宽度的一半

如果你想保持相同的HTML,你仍然可以使用这种技术来完成同样的事情,只需确保在你的replacediv上执行position: relative,这样任何absolutely位置的子对象都可以相对于它进行定位。

如果您希望容器中绝对定位的元素相对于容器定位,请将position: relative;添加到容器中:

#replace {
  position: relative;
  width: 950px;
  height: 500px;
}

然后设置为要定位的项目的最高值。这里需要注意的一点是,您的#replacediv是这里的容器,但它比#contentdiv小,所以当您定位#modal时,您必须给它特定的像素值,以使它位于#content的中心。

最新更新