给定以下CSS
li.menuitem{
position:relative;
top:0;
left:20px;
display:inline;
我希望每个 li 比没有相对位置时更靠左 20 像素。
但是,当我更改 left, all 的值时,如果菜单项相对于左侧位置一起移动,会发生什么情况。换句话说,元素之间的空间不会改变。
虽然还有其他方法可以实现我想要的效果,但我很好奇为什么两个元素都移动了,但两者之间的距离却没有改变。
谢谢, -dmd-
最佳答案
因为这就是 margin-left
的用途。
举个例子:如果你和我并排走,我们都向前走 20 步,你和我仍然是并排的。
同样,position: relative
不考虑周围其他 position: relative
元素的新定位。它们都相对于它们自然所在的位置移动,而不是相对于其他元素现在所在的位置。
MDN entry对于 position: relative
状态:
This keyword lays out all elements as though the element were not positioned, and then adjust the element's position, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned).
关于HTML 位置 :relative,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37512718/