CSS利用弹性盒flex布局模拟固定定位的效果

118 阅读1分钟

想要实现下面的效果,我们一般会想到固定定位:

screenshots.gif

但是其实也可以用,flex布局来实现。

这里的原理就是:在 Flex 布局中,当父元素 .box 的高度不够容纳其所有子元素时,Flex 布局会自动将剩余空间平均分配给所有子元素,实现自适应布局。

接下来开始实例模拟

我们定义1个BOX容纳main和footer

Box设置弹性盒,并给100vh.

而footer则是固定的30px高度


 <style>
      * {
        margin: 0;
        padding: 0;
        list-style: none;
        box-sizing: border-box;
      }
      .box {
        width: 100%;
        height: 100vh;
        display: flex;
        flex-direction: column;
        //纵向
      }
      .main {
        background: pink;
        width: 100%;
        height: 1900px;
        flex: 1;
        overflow-y: auto;
      }
      .footer {
        width: 100%;
        height: 30px;
        background: skyblue;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <div class="main">
        Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quo quam
        adipisci voluptas blanditiis quis quaerat rem dolores deleniti ipsum lpa
        voluptates alias dolor quasi eveniet
      </div>
      <div class="footer"></div>
    </div>
  </body>

当main的内容太多了,此时box无法容纳。那么父元素box就开始分配高度

footer固定占据30px,剩下的交给main,因为main设置了flex1,所以是允许放大缩小的

所以,这样就实现了类似固定定位的效果。