css3 position定位—— sticky 定位

一.概念

sticky 定位

sticky 英文字面意思是粘,粘贴,所以可以把它称之为粘性定位。

position: sticky; 基于用户的滚动位置来定位。

粘性定位的元素是依赖于用户的滚动,在 position:relative 与 position:fixed 定位之间切换。

它的行为就像 position:relative; 而当页面滚动超出目标区域时,它的表现就像 position:fixed;,它会固定在目标位置。

元素定位表现为在跨越特定阈值前为相对定位,之后为固定定位。

这个特定阈值指的是 top, right, bottom 或 left 之一,换言之,指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。

注意: Internet Explorer, Edge 15 及更早 IE 版本不支持 sticky 定位。 Safari 需要使用 -webkit- prefix (查看以下实例)。

二.实例场景运用

一.头部滚动后固定定位

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>头部滚动后固定定位</title>

<style>

div.sticky {

position: -webkit-sticky;

position: sticky;

top: 0;

padding: 5px;

background-color: #cae8ca;

border: 2px solid #4CAF50;

}

</style>

</head>

<body>

<p>尝试滚动页面。</p>

<p>注意: IE/Edge 15 及更早 IE 版本不支持 sticky 属性。</p>

<div class="sticky">我是粘性定位!</div>

<div style="padding-bottom:2000px">

<p>滚动我</p>

<p>来回滚动我</p>

<p>滚动我</p>

<p>来回滚动我</p>

<p>滚动我</p>

<p>来回滚动我</p>

</div>

</body>

</html>

AI写代码

xml

结果演示:

二.到左侧底部时,右侧边滚动,左侧固定

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>.到左侧底部时,右侧边滚动,左侧固定</title>

<style>

div.sticky {

position: -webkit-sticky;

position: sticky;

top: -100vh;

padding: 5px;

background-color: #cae8ca;

border: 2px solid #4CAF50;

}

.left,

.right {

width: 50%;

float: left;

box-sizing: border-box;

}

.right .bottom {

padding-top: calc(100vh - 60px);

line-height: 30px;

}

.left .bottom {

color: #333;

margin-top: calc(100vh - 30px);

line-height: 30px;

height: 100vh;

background-color: red;

}

.left {

background-color: #ff01c7;

border: 2px solid #e64133;

}

.right {

background-color: #40abf2;

border: 2px solid #0431fa;

}

.clearfix::before,

.clearfix::after {

content: "";

display: table;

}

.clearfix::before {

clear: both;

height: 0;

}

.clearfix::after {

clear: both;

height: 0;

}

</style>

</head>

<body>

<div class="clearfix">

<div class="left sticky">

我是粘性定位如果左侧滚动完,让我距离顶部一个屏幕宽度fixed

<div class="bottom">我是底部</div>

</div>

<div class="right">

<p class="bottom">来回滚动我第一屏</p>

<p class="bottom">来回滚动我第二屏</p>

<p class="bottom">来回滚动我第三屏</p>

<p class="bottom">来回滚动我第四屏</p>

<p class="bottom">来回滚动我第五屏</p>

</div>

</div>

</body>

</html>

AI写代码

xml

结果演示:

三.总结

当页面滚动超出目标区域时,它的表现就像 position:fixed;,它会固定在目标位置