基本用法
粘性定位可以被认为是相对定位和固定定位的混合。元素在跨越特定阈值前为相对定位,之后为固定定位
使用sticky时要注意几件事
一 首先,使用粘性布局须指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。
二 sticky是容器相关的,也就是说sticky的特性只会在它所处的容器中生效,如下案例,dt元素设置了sticky,在页面滚动时只会在每个dl容器中有粘性效果
三 当设置了sticky的元素的父元素(包含sticky元素多个层级的父元素)其中一个设置了overflow:hidden,会让sticky失效,原因,overflow:hidden也是一个滚动容器,sticky相对于这个容器吸附,而overflow:hidden的容器又会随着body的滚动而滚动,看起来就像未设置sticky吸附效果一样
知乎网友的详细解析:zhuanlan.zhihu.com/p/107242529
Let's try try ~
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>粘性定位-不生效原因</title>
<style>
* {
box-sizing: border-box;
}
dl {
margin: 0;
padding: 24px 0 0 0;
}
dt {
position: -webkit-sticky;
position: sticky;
top: -1px;
background: #B8C1C8;
border-bottom: 1px solid #989EA4;
border-top: 1px solid #717D85;
color: #FFF;
font: bold 18px/21px Helvetica, Arial, sans-serif;
margin: 0;
padding: 2px 0 0 12px;
}
dd {
font: bold 20px/45px Helvetica, Arial, sans-serif;
margin: 0;
padding: 0 0 0 12px;
white-space: nowrap;
}
dd+dd {
border-top: 1px solid #CCC
}
.tip {
border: 2px solid greenyellow;
border-radius: 10px;
padding: 5px;
font-size: 16px;
}
.tow-container {
/*或者换成.wrap */
overflow: hidden;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div class="wrap">
<dl>
<dt>A-滚动会吸附</dt>
<dd>Andrew W.K.</dd>
<dd>Apparat</dd>
<dd>Arcade Fire</dd>
<dd>At The Drive-In</dd>
<dd>Aziz Ansari</dd>
</dl>
<dl class="tow-container">
<!-- 父元素dl设置了overflow:hiddenh后,C吸附效果失效 -->
<dt>C-这个不会吸附奥</dt>
<dd>Chromeo</dd>
<dd>Common</dd>
<dd>Converge</dd>
<dd>Crystal Castles</dd>
<dd>Cursive</dd>
</dl>
<dl>
<dt>E</dt>
<dd>Explosions In The Sky</dd>
</dl>
<dl>
<dt>T</dt>
<dd>Ted Leo & The Pharmacists</dd>
<dd>T-Pain</dd>
<dd>Thrice</dd>
<dd>TV On The Radio</dd>
<dd>Two Gallants</dd>
</dl>
</div>
</body>
</html>