CSS“位置:固定”与父级一起移动

问题描述 投票:0回答:1

带有“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>

html css
1个回答
0
投票

位置:固定;属性相对于视口而不是其父元素定位元素。在您的情况下,子 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>

© www.soinside.com 2019 - 2024. All rights reserved.