我有一个简单的2列布局,带有一个脚注,可以清除标记中的左右div。我的问题是,我不能让页脚留在所有浏览器的页面底部。如果内容向下推页脚,它就会起作用,但情况并不总是如此。
当前回答
一个快速简单的解决方案,使用flex
将html和body的高度设置为100%
html,
body {
width: 100%;
height: 100%;
}
将主体显示为具有列方向的flex:
body {
min-height: 100%;
display: flex;
flex-direction: column;
}
为main添加flex-grow: 1
main {
flex-grow: 1;
}
flex-grow指定应将伸缩容器中剩余空间的多少分配给项(伸缩增长因子)。
*, *::after, *::before{ margin: 0; padding: 0; box-sizing: border-box; } html, body { width: 100%; height: 100%; } body { min-height: 100%; display: flex; flex-direction: column; } main { flex-grow: 1; } footer{ background-color: black; color: white; padding: 1rem 0; display: flex; justify-content: center; align-items: center; } <body> <main> <section > Hero </section> </main> <footer > <div> <p > © Copyright 2021</p> </div> </footer> </body>
其他回答
大多数答案使用固定值的css。虽然它可能工作,但当页脚更改时,需要调整页脚大小的固定值。另外,我使用的是WordPress,不想打乱WordPress主题为你定义的页脚大小。
我用一点javascript解决了这个问题,只在需要时触发。
var fixedFooter = false;
document.addEventListener("DOMContentLoaded", function() {fixFooterToBottom();}, false);
window.addEventListener("resize", function() {fixFooterToBottom();}, false);
function fixFooterToBottom()
{
var docClientHeight = document.documentElement.clientHeight;
var body = document.querySelector("body");
var footer = document.querySelector("footer");
fixedFooter = fixedFooter ? (body.clientHeight + footer.clientHeight ) < docClientHeight : body.clientHeight < docClientHeight;
footer.style.position = fixedFooter ? "fixed" : "unset";
footer.style.left = fixedFooter ? 0 : "unset";
footer.style.right = fixedFooter ? 0 : "unset";
footer.style.bottom = fixedFooter ? 0 : "unset";
}
你可以使用position: absolute following将页脚放在页面的底部,但要确保你的两列有适当的边距-底部,这样它们就不会被页脚遮挡。
#footer {
position: absolute;
bottom: 0px;
width: 100%;
}
#content, #sidebar {
margin-bottom: 5em;
}
在我的网站上,我总是使用:
position: fixed;
...在我的CSS页脚。将它固定在页面底部。
一个解决方案是为盒子设置最小高度。不幸的是,IE似乎并没有很好地支持它(意外)。
一个类似于@gcedo的解决方案,但不需要添加中间内容来向下推页脚。我们可以简单地添加margin-top:auto到页脚,不管它的高度或上面内容的高度,它都会被推到页面的底部。
身体{ 显示:flex; flex-direction:列; 最小高度:100 vh; 保证金:0; } .content { 填充:50 px; 背景:红色; } .footer { margin-top:汽车; 填充:10 px; 背景:绿色; } < div class = "内容" > 这里有些内容 < / div > <页脚类= >“页脚” 一些内容 < /页脚>