CSS实现页面底部固定的三种常用方法

  发布时间:2023-09-14 16:45:41   作者:C_心欲无痕   我要评论
在日常开发中,在移动端经常会有一些按钮需要固定在页面的底部(比如:提交按钮,发布按钮,确定按钮,下一步…等等),所以这边总结了3种比较常用好使的固底方法,需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

效果图如下:

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>

到此这篇关于CSS实现页面底部固定的三种常用方法的文章就介绍到这了,更多相关CSS页面底部固定内容请搜索程序员之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持程序员之家!

相关文章

最新评论

?


http://www.vxiaotou.com