经典布局之粘连布局(Sticky footers)

166 阅读1分钟

需求场景

  1. 页面内容不够长的时候,页脚块粘贴在视窗底部
  2. 如果内容足够长时,页脚块会被内容向下推送

解决方案

方案1: Flexbox

html结构:

<body>
    <main></main>
    <footer></footer>
</body>

css样式:

body {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    main {
        width: 100%;
        flex: 1;
    }
    footer {
        width: 100%;
    }
}

该方案footer不必设置固定高度且代码简洁,是较佳的现代css解决方案

方案2: calc计算

html结构:

<body>
    <main></main>
    <footer></footer>
</body>

css样式:

body {
    min-height: 100vh;
    main {
        width: 100%;
        min-height: calc(100vh - 150px);
    }
    footer {
        height: 150px;
        width: 100%;
    }
}

利用css的calc方法计算main内容的最小高度

方案3: 容器负margin + 伪元素占位

html结构:

<body>
    <main></main>
    <footer></footer>
</body>

css样式:

main {
   min-height: 100vh;
   margin-bottom: -150px;
   &::after {
     content: "";
     display: block;
     height: 150px;
   }
}
footer {
  height: 150px;
  width: 100%;
  &::after {
    height: 150px;
  }
}

利用负值margin和伪元素实现Sticky footers布局

方案4: 底部负margin

html结构:

<body>
    <main>
        <div class="wrap"></div>
    </main>
    <footer></footer>
</body>

css样式:

main {
    width: 100%;
    min-height: 100vh;
    background: rgba(7, 17, 27, 0.8);
    .wrap {
        padding-bottom: 100px; // sticky布局关键点
    }
}
footer {
    width: 100%;
    height: 100px;
    margin-top: -100px; // sticky布局关键点
    background: orange;
}

原理也是利用负值margin,只是将方案3的伪元素用wrap标签代替

演练场