//css
.box2{
width: 100%;
height: 100px;
background-color: black;
position: fixed;
top: 0;
left: 0;
}
.box3{
width: 100%;
height: 100px;
background-color: red;
margin-top: 200px;
}
//html
<div class="box1">
<div class="box2"></div>
<div class="box3"></div>
</div>
根据如上代码可以看到,box2因为position:fixed
的原因,是没有被包裹进box1中的:
但是当给box1加上padding: 0.1px
(值>0.1px都可以)之后,box2就被包裹进了box1:
想请问一下这是为什么?有没有什么办法不给box1加padding也让box2被包裹进box1?如果没有的话如何让box2不用position:fixed
也达到固定头部的效果?
原因
其实,
box2
从来没有被包裹进box1
。之所以出现这种效果,仅仅是因为
box1
没有padding-top
的时候,box3
的margin-top
会与box1
的上边距及body
的上边距折叠而已,此时,仅有box3
的内容区被算在box1
的内容区中;box1
有了padding-top
(或border-top
)后,box3
的上边距也会被计算在box1
的内容区中。不用
fixed
的方法下面是一种可供参考的方法