解决position: fixed;遮挡其他邻近模块内容的问题

问题描述

由于位置属性值fixed的设置,导致底部button部分在文档流中不占据文档流位置,所以导致底部内容被遮挡,无法正常展示。具体如下图所示:固定在底部的【取消/确定】button按钮遮挡底部【添加工作经验】按钮内容。

 问题引发分析

因为fixed元素脱离了正常文档流,所以relative元素的原本位置向上提了,产生了覆盖的行为。

需要添加marginor padding属性到下层内容组件上,使其发生向下偏移,不再被覆盖。

top、margin-top的区别:(此处参考其他作者,链接:https://juejin.cn/post/6986935474635931656)

  1. margin-top 属性设置元素的上外边距。是盒子模型的组成部分。它可以推开周围元素。注意相邻块元素的垂直边距会塌陷。
  2. 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>

image-20210720114103390.png

当header应用fixed样式后,它将悬浮于页面上方,覆盖下面的content组件:

.header {
        height: 50px;
        background-color: red;
        position: fixed;
        display: flex;
        top: 0;
        width: 100%;
        z-index: 1000;
    }

 

image-20210720114249714.png

 

解决方法

方法一:给内容设置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;
    }

效果:

image-20210720165837194.png

方法二:

用空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>

 效果:

image-20210720170305381.png

方法三:

下图主要使用position: sticky;属性值来使得脱离文档流的内容在文档中占据正常的文档流空间,因此fixed属性值覆盖问题得以解决!

 参考文档:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值