admin管理员组

文章数量:1611904

position:sticky是css定位新增属性;可以说是static(没有定位) 和 固定定位fixed 的结合;它主要用在对 scroll 事件的监听上;简单来说,在滑动过程中,某个元素距离其父元素的距离达到 sticky 粘性定位的要求时(比如top:100px);position:sticky这时的效果相当于fixed定位,固定到适当位置

position 的其他定位

  • absolute: 生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置通过"left", “top”, “right” 以及 “bottom” 属性进行规定。

  • fixed: 生成固定定位的元素,相对于浏览器窗口进行定位(老IE不支持),元素的位置通过"left", “top”, “right” 以及 “bottom” 属性进行规定。

  • relative: 生成相对定位的元素,相对于其正常位置进行定位,不脱离文档流。

  • static: 默认值,没有定位,元素出现在正常的文档流中(忽略 top, bottom, left, right 或者 z-index 声明)。inherit规定应该从父元素继承 position 属性的值。

sticky定位

  1. sticky 只能在父容器为 overflow: scroll中使用, 而且会根据最近的父容器(overflow:scroll)产生效果
  2. 必须规定 top, left ,right, bottom 中的一种, 否则 stikcy 定位相当于 relative
  3. 如果定义了 topbottom 属性. 那么父容器 height不能低于 top 或者 bottom的值
  4. sticky 属性目前在安卓上适配度不高, 所以 web 在安卓上慎用 sticky 属性
<style>
			div.father {
				width: 400px;
				height: 400px;
				overflow: scroll;
				background-color: red;
			}

			div#son-1 {
				background-color: green;
				width: 300px;
				height: 300px;
				overflow: scroll;
				margin-bottom: 30px;
			}

			div#son-1 h2 {
				width: 100px;
				height: 20px;
				background-color: pink;
				position: sticky;// 寻找在最近父元素为 scroll 属性的
				top: 0;
			}
			div#son-2 {
				width: 300px;
				height: 300px;
				background-color: blue;
				position: sticky;
			}
</style>

		<div class="father">
			<div id="son-1">
				<h2>hahahaha</h2>
				<h2>hahahaha</h2>
				<h2>hahahaha</h2>
				<h2>hahahaha</h2>
				<h2>hahahaha</h2>
				<h2>hahahaha</h2>
				<h2>hahahaha</h2>
				<h2>hahahaha</h2>
				<h2>hahahaha</h2>
				<h2>hahahaha</h2>
				<h2>hahahaha</h2>
				<h2>hahahaha</h2>``
			</div>
			<div id="son-2">
				<h2>123123123</h2>
			</div>

			<div id="son-3">
				<h2>123123123</h2>
			</div>

			<div id="son-3">
				<h2>123123123</h2>
			</div>
</div>

div#son-1 h2 中的 position:sticky 会找离的最近的父元素为 overflow:scroll的元素(div#son-1)进行粘贴效果. 而不是 div.father

学习该部分内容视频地址: https://www.bilibili/video/BV1X4411z7ZW?p=13.

本文标签: 粘性PositionSticky