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