利用overflow失效巧妙实现类似position:fix的效果

<style>
*{margin:0;padding:0;}
html{overflow:hidden;}
.page{height:100vh;width:100%;overflow-y:scroll;background:#999;}
.content{height:3000px;width:80%;margin:0 auto;background:#0FF;}
.fix{height:0;overflow:hidden;text-align:right;}/* 此处利用子元素绝对定位absolute后父元素overflow:hidden失效的情况使需要固定的元素显示出来 */
.fix_element{position:absolute;top:50%;background:#F00;height:50px;width:50px;}
</style>

<body>
<div class="page">    
    <div class="content">
        <div class="fix">
        &nbsp;<a href="#" class="fix_element"></a>
        </div>
    </div>
</div>
</body>

首先将fix里加入一个空格&nbsp在需要固定显示元素的前面,将fix的height:0;overflow:hideen;右侧对其,紧接着将fix_element绝对定位,利用absolute的跟随性让其在空格&nbsp后显示;在设置top:50%。之后将父元素fixoverflow:hidden即可(利用子元素绝对定位后父元素overflow失效的情况让fix显示出来)。

虽然代码显得冗长,更多的是为了拓展下思路,利用不同的方法解决问题

猜你喜欢

转载自www.cnblogs.com/qianphong/p/10389614.html