CSS实现Footer置底

来源:互联网 发布:淘宝香港代购靠谱吗 编辑:程序博客网 时间:2024/06/05 10:56

页面置底就是让网页的footer部分始终在浏览器窗口的底部。

实现方法:

方法1:给html高度设置100%,body设置min-height:100%,把底部绝对定位到body的底部

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title>    <style>        *{            padding: 0;            margin: 0;        }        html{            height: 100%;        }        body{            position: relative;            min-height: 100%;        }        .footer{            position: absolute;            bottom: 0;            left: 0;            width: 100%;            height: 100px;            background-color: #f00;        }    </style></head><body><div class="footer"></div>  </body></html>

方法2:将内容部分的底部外边距设置为负数,把内容的最小高度设为100%,再利用内容部分的负底部外边距值来达到当高度不满时,页脚保持再窗口底部,当高度超出则随之推出的效果。

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title>    <style>        html,body{            height: 100%;            margin: 0;        }        .wrapper{            min-height: 100%;            /*等于footer的高度*/            margin-bottom: -50px;        }        .footer,.push{            height: 50px;        }    </style></head><body><div class="wrapper">    content    <div class="push"></div></div><div class="footer"></div>  </body></html>
这个方法需要容器里有额外的占位元素(如.push)

需要注意的时.wrapper的margin-bottom值需要和.footer的负的height值保持一致,这一点不是太友好。


方法3:将页脚的顶部外边距设为负数

在容器上使用负margin-top,给内容外增加父元素,并让内容部分的底部内边距与页脚高度的值相等。

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title>    <style>        html,body{            height: 100%;            margin: 0;        }        .content{            min-height: 100%;        }        .content-inside{            padding: 20px;            padding-bottom: 50px;        }        .footer{            height: 50px;            margin-top: -50px;            background-color: #f00;        }    </style></head><body><div class="content">    <div class="content-inside">        content    </div></div>  <div class="footer"></div></body></html>

这个方法需要多添加一个包裹层


方法4:使用calc()设置内容的高度
<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title>    <style>        html,body{            margin: 0;        }        .content{            min-height: calc(100vh - 50px);        }        .footer{            height: 50px;            background-color: #f00;        }    </style></head><body><div class="content">    content</div>  <div class="footer"></div></body></html>

方法5:使用flexbox弹性盒布局

以上三种方法的footer高度都说固定的,通常来说不利于网页布局:内容会改变,它们都说弹性的,一旦内容超出固定高度就会破坏布局,所以给footer使用flexbox,让它的高度可以变大变小。

以上方法,第一种方法是自己总结的,其他方法是参考文章《css 5种方式实现Footer置底》

0 0