带有“position:fixed”的元素必须保持固定在视口上。但在下面的示例中,固定元素与其父元素一起移动。谁能解释为什么元素没有固定到视口?
<div style="height: 100vh; background-color: lightblue; margin-left: 300px;">
<div style="position: fixed; background-color: tomato; width: 100px; height: 100px;">
</div>
</div>
位置:固定;属性相对于视口而不是其父元素定位元素。在您的情况下,子 div 的位置:固定;与视口一起移动,这意味着即使您滚动页面,它也会保持在屏幕上的同一位置。
如果你希望子 div 不随父 div 移动,请删除“position:fixed”样式
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div style="height: 100vh; background-color: lightblue; margin-left: 300px;">
<div style="background-color: tomato; width: 100px; height: 100px;">
</div>
</div>
</body>
</html>