问题描述:
由于位置属性值fixed的设置,导致底部button部分在文档流中不占据文档流位置,所以导致底部内容被遮挡,无法正常展示。具体如下图所示:固定在底部的【取消/确定】button按钮遮挡底部【添加工作经验】按钮内容。
问题引发分析:
因为fixed元素脱离了正常文档流,所以relative元素的原本位置向上提了,产生了覆盖的行为。
需要添加margin
or padding
属性到下层内容组件上,使其发生向下偏移,不再被覆盖。
top、margin-top的区别:(此处参考其他作者,链接:https://juejin.cn/post/6986935474635931656)
- margin-top 属性设置元素的上外边距。是盒子模型的组成部分。它可以推开周围元素。注意相邻块元素的垂直边距会塌陷。
- top 属性规定元素的顶部边缘。该属性定义了一个定位元素的上外边距边界与其包含块上边界之间的偏移。如果希望元素对周围元素没有影响,可以使用top与绝对定位元素
样例展示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
.outer-container {
margin: 0 auto;
display: block;
max-width: 100%;
}
.header {
height: 50px;
background-color: red;
display: flex;
width: 100%;
}
.content {
height: 100px;
background-color: yellow;
border: 2px black solid;
display: block;
position: relative;
/*methods1 */
/*margin-top: 50px;*/
}
.footer {
height: 50px;
background-color: green;
postion: relative;
}
</style>
<body>
<div class="outer-container">
<div class="header">I am the header</div>
</div>
<div class="content">I am the content1</div>
<div class="content">I am the content2</div>
<div class="footer">I am the footer</div>
</body>
</html>
当header应用fixed样式后,它将悬浮于页面上方,覆盖下面的content组件:
.header {
height: 50px;
background-color: red;
position: fixed;
display: flex;
top: 0;
width: 100%;
z-index: 1000;
}
解决方法:
方法一:给内容设置margin-top,同时设置header中的top:0和z-index,否则引起margin-top失效。
.content {
height: 100px;
background-color: yellow;
border: 2px black solid;
display: block;
position: relative;
/*methods1 */
margin-top: 50px;
}
效果:
方法二:
用空div占位,同时设置body margin=0,使div的位置相对于视窗口无边距,变得可计算。
.empty-content{
position: relative;
display: block;
height: 50px;
}
<body>
<div class="outer-container">
<div class="header">I am the header</div>
</div>
<div class="empty-content"></div>
<div class="content">I am the content1</div>
<div class="content">I am the content2</div>
<div class="footer">I am the footer</div>
</body>
效果:
方法三:
下图主要使用position: sticky;属性值来使得脱离文档流的内容在文档中占据正常的文档流空间,因此fixed属性值覆盖问题得以解决!
参考文档: