将footer固定在页面底部的实现方法,附实例

方法1:footer高度固定+绝对定位

<style>
html{height:100%;}
body{min-height:100%;margin:0;padding:0;position:relative;}
header{background-color: #ffe4c4;}
main{padding-bottom:100px;background-color: #bdb76b;}/* main的padding-bottom值要等于或大于footer的height值 */
footer{position:absolute;bottom:0;width:100%;height:100px;background-color: #ffc0cb;}
</style>

<body>
    <header>header</header>
    <main>content</main>
    <footer>footer</footer>
</body>

test1实例

方法2.1:footer高度固定+margin负值

<style>
html,body{height:100%;margin:0;padding:0;}
.container{min-height:100%;}
header{background-color: #ffe4c4;}
main{padding-bottom:100px;background-color: #bdb76b;}/* main的padding-bottom值要等于或大于footer的height值 */
footer{height:100px;margin-top:-100px;background-color: #ffc0cb;}/* margin-top(负值的)高度等于footer的height值 */

</style>

<body>
    <div class="container">
        <header>header</header>
        <main>main content</main>
    </div>
    <footer>footer</footer>
</body>

test2.1实例

方法2.2:footer高度固定+margin负值

<style>
html,body{height:100%;margin:0;padding:0;}
header{background-color: #ffe4c4;}
.container{min-height:100%;margin-bottom:-100px;background-color: #bdb76b;}
.empty,footer{height:100px;background-color: #ffc0cb;}

</style>

<body>
    <div class="container">
        <header>header</header>
        <main>main content</main>
        <div class="empty"></div>
    </div>
    <footer>footer</footer>
</body>

test2.2实例

方法3:footer高度任意+js

<style>
html,body{margin:0;padding: 0;}
header{background-color: #ffe4c4;}
main{background-color: #bdb76b;}
footer{background-color: #ffc0cb;}

/* 动态为footer添加类fixed-bottom */
.fixed-bottom {position: fixed;bottom: 0;width:100%;}

</style>

<body>
    <header>header</header>
    <main>main content</main>
    <footer>footer</footer>

	<script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
	<script type="text/javascript">	
	$(function(){
	    function footerPosition(){
	        $("footer").removeClass("fixed-bottom");
	        var contentHeight = document.body.scrollHeight,	//网页正文全文高度
	            winHeight = window.innerHeight;				//可视窗口高度,不包括浏览器顶部工具栏
	        if(!(contentHeight > winHeight)){				//当网页正文高度小于可视窗口高度时,为footer添加类fixed-bottom
	            $("footer").addClass("fixed-bottom");
	        } else {
	            $("footer").removeClass("fixed-bottom");
	        }
	    }
	    footerPosition();
	    $(window).resize(footerPosition);
	});
	</script>

test3实例

参考:
https://zhuanlan.zhihu.com/p/22936824?refer=nangit
http://www.jianshu.com/p/4896e6936ce3
http://www.cnblogs.com/wudingfeng/archive/2012/06/29/2569997.html
https://www.zhihu.com/question/26510142/answer/33034801

欢迎关注我的微信公众号:

 

如无特殊说明,文章均为本站原创,转载请注明出处!

《将footer固定在页面底部的实现方法,附实例》有一个想法

发表回复

您的电子邮箱地址不会被公开。