前几天被人问,「如何把元素固定在容器底部」。(原本想间接把 demo 地址给他,后果没找到,那么明天咱们来补一下)

Demo 地址

想法&思路

如果是页面底部,咱们能够间接 position: fixed;bottom: 0; 基于浏览器定位间接实现。

然而他要的成果是基于父级容器,那么咱们必须要应用其余伎俩来定位了

  1. relative 来限度 absolute,而后 bottom: 0,然而在内容过长的时候会导致显示异样。所以咱们须要做外部滚动。
  2. 如果做外部滚动,那么咱们只有能够撑开盒子即可。不须要相对定位了

应用 flex 实现

  • 父级应用 flex 布局,column 垂直排列。
  • 父级定高(height、maxHeight),.content 子级 flex:auto; 主动撑开。 或者 .content 做高度限制。
  • footer 能够应用 absolute 加 padding 。或者齐全依赖文档流布局都能够

      .demo1{      position: relative;      padding-bottom: 40px;      display: inline-flex;      flex-direction: column;  }  .demo1 .footer{      position: absolute;      bottom: 0;      left: 0;right: 0;      margin: 0;  }  .demo1 .content{      overflow: auto;  }

calc 实现

如果不应用 flex ,那么咱们能够用 calc 来减去 header 和 footer 空间。

<style>    .demo3{        position: relative;    }    .demo3 .content{        overflow: auto;        max-height: calc(100% - 40px);    }</style>

absolute 实现

如果 calc 兼容性不太好,那么还能够应用 absolute 将所有元素都脱离文档流。

<style>    .demo4{        position: relative;    }    .demo4 .header,.demo4 .footer{        position: absolute;        margin: 0;        top:0;left:0 ;right:0;    }    .demo4 .footer{        top: auto;        bottom: 0;    }    .demo4 .content{        overflow: auto;        height: 100%;        padding-top: 30px;        padding-bottom: 30px;        margin: 0;        box-sizing: border-box;    }</style>