效果图
如下图所示,利用 position: sticky
属性轻松实现。
示例代码
新建一个 *.html
文件,一键复制运行起来。
<body>
<section class="content">
<div class="item">
我是悬浮吸顶区域
</div>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
<h1>我是数据...</h1>
</section>
</body>
<style>
/* 根节点(父容器) */
.content {
/* position: relative; */
background: #f1f1f1;
width: 300px;
height: 400px;
overflow: auto;
}
/* 子节点(悬浮吸顶外层容器) */
.item {
background: pink;
padding: 20px;
/* 核心属性,必须设置top,left或者bottom,right位置 */
position: sticky;
top: 0; left: 0;
/* 或: bottom: xx, right: xx */
}
</style>
当被其他高层级容器遮挡时,请设置 z-index
并超过它。