CSS同级元素position:fixed和margin-top共同使⽤的问
题
问题描述
想⽤CSS实现顶部固定的效果:
尝试margin-top加position:fixed实现,代码如下:css固定定位
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Test</title>
<style type="text/css">
.header {
position: fixed;
height: 20px;
width: 100%;
}
.content {
margin-top: 30px;
}
.
aside {
float: left;
width: 200px;
background: orange;
}
.main {
overflow: auto;
background: yellow;
}
</style>
</head>
<body>
<div class="header">123</div>
<div class="content">
<div class="aside">aside</div>
<div class="main">main</div>
</div>
</body>
</html>
结果header没有定位在顶部,⽽是空出了content的margin-top距离:
按照position:fixed的定义,header已经脱离⽂档流,应该不会受到content布局影响,但结果并⾮如此。
问题探究
3.body设置padding-top:会空出body的padding-top的距离,可实现预期效果。
4.body设置margin-top:会空出max(body->margin-top,content->margin-top)的距离。
5.给header设置top,如top: 0;:不受body和content的布局影响。
TBD:之后补充详细的测试代码和效果图( ̄∇ ̄)...
总结
归根结底是margin-top塌陷问题对position:fixed的影响。⾸先,对于position:fixed元素,如果不指定top,它在垂直⽅向上的参考原点是body盒模型的content的上边界。如果指定top,它在垂直⽅向上的
参考原点才是我们常说的视窗(viewport)的上边界,left和⽔平⽅向同理。这⾥的参考原点是指fixed元素布局时的参考对象,⼀旦确定,即便页⾯被下拉,body上边界上
移,fixed元素位置也不再改变。其次,因为margin-top塌陷问题,设置content的margin-top后,body的content部分会下移,即参考原点下移,所以fixed元素会空出margin-top的距离。
所以,可以从两⽅⾯解决这个问题:
1.将参考原点改为视窗:给fixed元素设置top。
2.解决margin-top塌陷问题,更多⽅法见下⽅链接:
1)给body设置padding-top。
2)给body设置border,border颜⾊和背景⾊⼀致。
3)给body设置position:fixed,这种会导致body的滚动条消失。
先将就看着呀~忙过这阵来完善(允悲)(允悲)。。。
TBD:content名字和盒模型content重啦待改...
不懂position:fixed?=> position|MDN
不懂margin-top塌陷?=> margin-top塌陷问题的现象与解决
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论