让页脚始终固定在底部,最佳方法是使用absolute定位
首先需要设置html的最小高度为100%,这样页面内容不足时,仍能够铺在底部。
实现代码如下:
<!doctype html>
<html>
页面内容<br>
页面内容<br>
页面内容<br>
页面内容<br>
页面内容<br>
页面内容<br>
页面内容<br>
<footer class="footer">
页脚内容
</footer>
<style>
html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 60px; /* Margin bottom by footer height */
}
.footer {
position: absolute;
bottom: 0;
height: 60px; /* Set the fixed height of the footer here */
background-color: #f5f5f5;
}
</style>
<html>
这种方法需要给body设置一些margin-bottom,适合footer高度固定的页脚。
怎么实现高度变化的footer固定在底部?我们可以使用变换:transform: translateY(100%);
<!doctype html>
<html>
页面内容<br>
页面内容<br>
页面内容<br>
页面内容<br>
页面内容<br>
页面内容<br>
最后一行
<footer class="footer">
页脚内容
</footer>
<style>
html {
position: relative;
min-height: 100%;
}
.footer {
position: absolute;
bottom: 0;
background-color: #f5f5f5;
transform: translateY(100%);
}
</style>
<html>
显而易见,美中不足的是,当页面内容不足时导致页面高于100%。
如果你觉得这种方案也不好,可以使用 fixed,或javascript
使用fixed时,你仍然需要在body中补一个固定的padding
当然,你可以使用javascript动态获取footer的高度, 然后再加到body的padding-bottom,因为javascript非常灵活,它的实现方式太多了,不予介绍。
对于会变化高度的页脚,如果不使用javascript,很难完美的固定住。如果是一般网页,推荐固定footer高度,如果是框架,推荐使用transform,很少使用javascript。
本篇完,还有疑问?留下评论吧