当前位置: 首页 > web>阅读正文

html页脚铺满在底部

2022.7.3 朱丰华 1800 次 留下评论 1795字

让页脚始终固定在底部,最佳方法是使用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非常灵活,以下给一种简单的方案:

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>bootstrap 101</title>
    <link rel="stylesheet" href="https://www.52dixiaowo.com/tools/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css">
    <script src="https://www.52dixiaowo.com/tools/npm/jquery@1.12.4/dist/jquery.min.js"></script>
    <script src="https://www.52dixiaowo.com/tools/npm/bootstrap@3.4.1/dist/js/bootstrap.min.js"></script>
</head>

<body>
    <div id="content">
    <h1 style="margin:0px;">Hello,Bootstrap3!</h1>

    </div>
    <div id="footer">
        <p style="text-align:center;margin:0px;">copyright &copy; zhufenghua 2022</p>
    </div>

    <script>
        $(function() {
            const height = $("#footer").height();
            $("#content").css("min-height", (document.documentElement.clientHeight - height) + 'px');
        })
    </script>
</body>

</html>

本篇完,还有疑问?留下评论吧

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注