我正在尝试在父元素的中心创建一个元素。我的问题是如何使它始终以响应为中心。
我有类似的东西
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; margin-right: auto; left: 0; right: 0;
。
另外,您应该将宽度添加到父元素,然后子代将知道中心在哪里。在您的情况下,.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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句