事实上,我有时发现设置50vw
只是使元素大约是它应该有的距离的一半。
为什么会这样?我在这里错过了什么?
您还需要减去项目宽度的一半。例如,您可以使用保证金来执行此操作。还有其他选择,例如计算。
请看这个小提琴的例子:https://jsfiddle.net/cgsymvyg/1/
#box1 {
border: 1px solid red;
background: green;
color: white;
width: 100px;
height: 100px;
position: absolute;
left: 50vw;
}
#box2 {
top: 200px;
border: 1px solid green;
background: red;
color: white;
width: 100px;
height: 100px;
position: absolute;
left: 50vw;
margin-left: -50px;
}
#box3 {
top: 400px;
border: 1px solid yellow;
background: blue;
color: white;
width: 100px;
height: 100px;
position: absolute;
left: calc(50vw - 50px);
}
<div id="box1">
Box 1
</div>
<div id="box2">
Box 2
</div>
<div id="box3">
Box 3
</div>