我无法将 position: relative
元素 ( https://jsfiddle.net/qL0c8cau/ ) 中的内部 position: absolute
元素居中:
html,body,div {margin:0;padding:0;}
.one {
position: relative;
margin: 50px auto;
width: 200px;
height: 100px;
background: #900;
}
.two {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto;
background: #0f0;
opacity: 0.3;
height: 160px;
width: 400px;
}
<div class="one">
<div class="two"></div>
</div>
我看不出有什么问题。我设置的一切都是正确的,但由于某种原因它没有水平对齐。
我在这里做错了什么?
最佳答案
将此添加到您的 CSS 中
.two {
position: absolute;
top:50%;
left: 50%;
transform:translate(-50%,-50%);
margin: auto;
background: #0f0;
opacity: 0.3;
height: 160px;
width: 400px;
}
此代码将确保,无论您的容器有多大,内部容器始终位于外部容器的中心。
html,body,div {margin:0;padding:0;}
.one {
position: relative;
margin: 50px auto;
width: 200px;
height: 100px;
background: #900;
}
.two {
position: absolute;
top:50%; /* this to center the box w.r.t to parent */
left: 50%;/* this to center the box w.r.t to parent */
/* Above 2 lines wont fully center it, the next line internally centers it, buy moving itself 50% left and top */
transform:translate(-50%,-50%);
margin: auto;
background: #0f0;
opacity: 0.3;
height: 160px;
width: 400px;
}
<div class="one">
<div class="two"></div>
</div>
关于html - 在相对元素内水平居中绝对元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50065698/