• CSS如何实现页面头部和底部固定,中间自适应的效果?
  • 发布于 2个月前
  • 285 热度
    0 评论
开局一张图

第一种.使用相对定位和绝对定位
注意:当页面高度高于可视窗口的时候(也就是出现了滚动条);这时如果再使用绝对定位 向上滑动的时候,就已经不固底了,因为页面进来定位只计算一次;

解决方案:使用fixed固定定位,永远把footer固定到底部,有滚动条也是不影响的;
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>堆代码 duidaima.com</title>
    <style>
        /* // 第一种方式 */
        .container {
            /* // 使用子绝父相 */
            position: relative;
            height: 100vh;
            background: #f1f3f4;
        }

        header,
        main,
        footer {
            height: 80px;
            line-height: 80px;
            width: 100%;
        }

        /* // 设置绝对定位 */
        footer {
            height: 60px;
            line-height: 60px;
            position: absolute;
            bottom: 0;
            left: 0;
        }
    </style>
</head>

<body>
    <div class="container">
        <header style="background: #f9cc9d">Header</header>
        <main style="background: #c3d08b">Content</main>
        <footer style="background: #2b93f5">Footer</footer>
    </div>
</body>

</html>
第二种 使用flex弹性布局,将footer的margin-top设置为auto
注意:在浏览器中,100vh的高度包括了底部的工具栏,而我们真实需要的高度其实是浏览器的可视高度也就是100%;
在使用100vh的时候,手机浏览器底部的操作栏可能会遮挡底部按钮;
所以这时页面的高度应该使用100%;
<template>
  <div class="container">
    <header style="background: #f9cc9d">Header</header>
    <main style="background: #c3d08b">Content</main>
    <footer style="background: #2b93f5">Footer</footer>
  </div>
</template>
<script>
export default {};
</script>
<style scoped lang="scss">
// 第二种方式
.container {
  display: flex;
  flex-direction: column; // 设置成上下排列方式
  height: 100vh;
  background: #f1f3f4;
  header,  main,  footer {
    height: 80px;
    line-height: 80px;
    width: 100%;
  }
  // 使用
  footer {
    margin-top: auto;
    height: 60px;
    line-height: 60px;
  }
}
</style>
第三种 通过css内置函数calc()动态计算内容的高度
min-height: calc(100vh - 130px); 130 其实就是 header和footer的高度;
<template>
  <div class="container">
    <header style="background: #f9cc9d">Header</header>
    <main style="background: #c3d08b">Content</main>
    <footer style="background: #2b93f5">Footer</footer>
  </div>
</template>

<script>
export default {};
</script>
<style scoped lang="scss">
// 第三种方式
.container {
  height: 100vh;
  background: #f1f3f4;
  header {
    height: 80px;
    line-height: 80px;
    width: 100%;
  }
  footer{
    height: 50;
    line-height: 50px;
  }
  // 内容区 130 其实就是 header和footer的高度
  main{
    min-height: calc(100vh - 130px);
  }
}
</style>

用户评论