CSS

实现底部(或顶部)固定

2019-07-25  本文已影响5人  奶酪凌

一,资料

CSS五种方式实现Footer置底
CSS3 calc()是怎么实现计算

二,一般操作

1.底部悬浮(position:fixed)

一般说页面中的某一部分要固定在底部或者是顶部的时候,大多数都是想到使用【position:fixed】,让div悬浮在底部或者顶部。

<div class="wrap">
        <div class="content"></div>
        <div class="free"></div>
        <div class="footer"></div>
</div>
//div.footer是固定在页面底部,固定高度,假如不固定高度,会有一定的遮挡住内容区域
//div.free是空出底部高度的内容,让内容区域正常显示出来。
<style>
.free{
    width:100%;
    height:50px;
}
.footer{
    position:fixed;
    bottom:0;
    left:0;
    right:0;
    width:100%;
    height:50px;
}
</style>

缺点:悬浮的层需要有固定高度,如果超过该高度,会破坏布局

2.底部悬浮(overflow:scroll)

<div class="wrap">
      <div class="content"></div>
      <div class="footer"></div>
</div>

<style>
html,body,.wrap{
  height:100%;
overflow:hidden;
}
.content{
/*在运算符前后都需要保留一个空格,否则不会生效*/
  heigth:calc(100% - 50px);
overflow-y:scroll;
}
.footer{height:50px;}
</style>

最后:使用calc来进行计算高度,同样需要固定一个高度
\color{red}{calc()函数支持 "+", "-", "*", "/" 运算;在运算符前后都需要保留一个空格}

image.png
<div class="wrap">
      <div class="content"></div>
      <div class="footer"></div>
</div>

<style>
html,body,.wrap{
  height:100%;
overflow:hidden;
}
.content{
  heigth:auto;
overflow-y:scroll;
}
</style>

<script>
  var Hbody = $(window).height();
  var Htop = $(".footer").height();
  var Hscroll = Hbody-Htop;
  $(".content").css("height",Hscroll);
</script>

最后:不是纯css操作,需要js来判断层的高度

3.flex布局

flex布局,适用于ie11以上的浏览器,例如谷歌等,手机上一般都适用。

<div class="wrap">
      <div class="content"></div>
      <div class="footer"></div>
</div>

<style>
html,body,.wrap{
  height:100%;
overflow:hidden;
}
.wrap{
 display:-webkit-box;
  display:-webkit-flex;
  display:flex;
  flex-direction:column;
}
.contant{
  -webkit-box-flex:1;
  -webkit-flex:1;
  flex:1;
  height: 100%;
  overflow-y: scroll;
}
</style>

利用flex的垂直布局,底部高度不进行设置,中间内容区域设置滚动,高度根据底部层高度进行变化,一屏显示。也可以运用到头部,底部固定,中间滚动。注意下flex的兼容情况

上一篇下一篇

猜你喜欢

热点阅读