为什么使用fixed定位后元素会出现这种情况?

我给div1设置position: fixed后 div2会跑到div1下面 然后我给div2设置margin-top: 30px后为什么div1也跟着下来了?这是为什么?出现这种情况怎么办解决?
图片描述

<!DOCTYPE html>
<html>
<head>
    <title></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <style type="text/css">
    body,html,div{margin: 0;padding: 0;}
    .div1{width: 100%;height: 30px;background-color: blue;position: fixed;}
    .div2{width: 100%;height: 100px;background-color: red;margin-top: 30px}
  </style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
</body>
</html>
阅读 4.9k
2 个回答

因为Fixed是绝对定位的一种,不占据实际文档空间
你可以把DIV1的透明的改为0.5,可以看见div2实际上有一部分是在div1下面的.
除了给div1加top值,也可以给div1一个什么属性都没有的父元素,并且给他一个兄弟元素,兄弟元素的高度为你div2的margin-top.
这样可以解决div1和div2重合的问题.
这个问题叫做fixed的高度坍塌,百度可以有更详细的解答

<!DOCTYPE html>
<html>
<head>
    <title></title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <style type="text/css">
    body,html,div{margin: 0;padding: 0;}
    .div1{width: 100%;height: 30px;background-color: blue;position: fixed; opacity: 0.5;}
    .div2{width: 100%;height: 100px;background-color: red;margin-top:40px;}
  </style>
</head>
<body>
    <div >
<div class="div1"></div>
<div style="height: 40px;"></div>
</div>
<div class="div2"></div>
</body>
</html>

div1加个top:0

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题