position: sticky; 粘性布局

2020-11-03  本文已影响0人  兜兜转转的小菊

粘性布局: 结合了 position:relative 和 position:fixed 两种定位于一体的特殊定位,适用于一些特殊场景。具体说明可查看 MDN-position
如下图:
要求滑动时固定第一行 ,第一列

样例.png
滑动后.png
   position: sticky;  /* 实现粘性布局 */
   top: 100px; /* 固定的位置为距离顶部100px的位置,当设置区域滑动到距离父窗口顶部100px的位置固定 */
   left: 100px; /* 固定的位置为距离左侧100px的位置,当设置区域向左滑动到距离父窗口左侧100px的位置固定 */
   z-index: 1; /* 显示层级 */
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>position: sticky; 粘性布局</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    .wrap{
      width: 100%;
      height: 100%;
    }
    /* 滚动的盒子区域 */
    .box{
      width: 800px;
      height: 500px;
      margin: 10px auto;
      overflow: auto;  /* 注意点1: 父窗口可设置滑动区域,如果没有这个,默认是body区域 */
    }
    .list{
      margin: 0;
      padding: 0;
      list-style: none;
      width: max-content; /* 注意点2: 可滑动区域一定要是超出盒子高宽的,这里直接取最大值,不设置可能会出现滚出一个屏幕,固定块消失 */
    }
    .list li span{
      display: inline-flex;
      justify-content: center;
      align-items: center;
      margin: 5px;
      width: 100px;
      height: 100px;
      font-size: 24px;
      color: #fff;
      background-color: yellowgreen;
      border: 1px solid #5e860c;
    }
    /* 设置第一行 固定在顶部 */
    .list li:first-child{
      position: sticky; /* 关键设置 position: sticky; */
      top: 0; /* 固定的位置为顶部 */
      z-index: 1; /* 显示层级 */
    }
    /* 设置第一列 固定在最左侧*/
    .list li span:first-child{
      position: sticky;
      left: 0; /* 定位left为0 */
      background-color: red;
    }
    .list li:first-child span{
      /* position: sticky;
      left: 0; // 加上这个会有另一种效果,像左滑动的时候,第一块总是被新来的替换
      top: 0; */ 
      background-color: #f7d014;
    }
    
  </style>
</head>
<body>
  <div class="wrap">
    <div class="box">
      <ul class="list">
        <li>
          <!-- span*100 -->
        </li>
        <!-- ... -->
      </ul>
    </div>
  </div>
</body>
</html>

3

上一篇 下一篇

猜你喜欢

热点阅读