我试图在父元素的中心创建一个元素 我的问题是如何让它始终响应地居中。
我有类似的东西
html
<div class="test">
<span class="d1">Test 1</span>
<span class="d2">Test 2</span>
</div>
CSS
.test {
position:relative;
}
.d1 {
width:300px;
height:200px;
background-color: #789845;
}
.d2 {
position: absolute;
top:40%;
left: ( not sure what to put here), I want this element always in the center no matter the width of browser is.
width: 100px;
background-color:#EEEE78;
}
我不确定如何设置 left
值,因为如果我设置一个静态值,它总是会因不同的浏览器宽度而有所偏差。有人可以帮我吗?非常感谢!
最佳答案
对于任何 absoulte
位置元素 - 只存在一个总体规则 margin-left: auto;右边距:自动;左:0;右:0;
。
此外,您应该为您的父元素添加宽度,这样 children 就会知道中心在哪里。在您的情况下,它是 .test
类, width: 100%;
(您可以根据需要更改它)。
.test {
position:relative;
width: 100%;
}
.d1 {
width:300px;
height:200px;
background-color: #789845;
}
.d2 {
position: absolute;
width: 100px;
background-color:#EEEE78;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
}
<div class="test">
<span class="d1">Test 1</span>
<span class="d2">Test 2</span>
</div>
关于html - 在我的案例中如何将绝对位置元素居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32193021/