在日常开发中,在移动端经常会有一些按钮需要固定在页面的底部(比如:提交按钮,发布按钮,确定按钮,下一步…等等);所以这边总结了3种比较常用好使的固底方法;

效果图如下:
在这里插入图片描述

1,使用相对定位和绝对定位

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

解决方案:使用fixed固定定位,永远把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 {
// 使用子绝父相
  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>

2,使用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>

3,通过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>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐