我有一个简单的2列布局,带有一个脚注,可以清除标记中的左右div。我的问题是,我不能让页脚留在所有浏览器的页面底部。如果内容向下推页脚,它就会起作用,但情况并不总是如此。
当前回答
flex解决方案对我来说是有效的,因为它使页脚变得有粘性,但不幸的是,将页面主体改为使用flex布局会使我们的一些页面布局发生变化,而且不是更好的。最后对我有用的是:
jQuery(document).ready(function() {
var fht = jQuery('footer').outerHeight(true);
jQuery('main').css('min-height', "calc(92vh - " + fht + "px)");
});
我从ctf0在https://css-tricks.com/couple-takes-sticky-footer/的回复中得到了这个
其他回答
一个快速简单的解决方案,使用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>
我没有任何运气在这一页上建议的解决方案,但最后,这个小技巧成功了。我将把它作为另一种可能的解决方案。
footer {
position: fixed;
right: 0;
bottom: 0;
left: 0;
padding: 1rem;
background-color: #efefef;
text-align: center;
}
我发明了一个非常简单的解决方法,对我来说非常有用。您只需在div中包装除页脚之外的所有页面内容,然后将min-height设置为视点减去页脚高度的100%。不需要在页脚或多个包装器div上进行绝对定位。
.page-body {min-height: calc(100vh - 400px);} /*将400px替换为页脚高度*/
使用绝对定位和z-index创建一个粘脚div在任何分辨率,使用以下步骤:
创建一个脚注div, position: absolute;底部:0;以及期望的高度 设置页脚的填充,以便在内容底部和窗口底部之间添加空白 创建一个容器div,用position: relative包装主体内容;最小高度:100%; 为主内容div添加底部填充,它等于高度加上页脚的填充 如果页脚被剪切,则设置页脚的z-index大于容器div
这里有一个例子:
<!doctype html> <html> <head> <title>Sticky Footer</title> <meta charset="utf-8"> <style> .wrapper { position: relative; min-height: 100%; } .footer { position: absolute; bottom:0; width: 100%; height: 200px; padding-top: 100px; background-color: gray; } .column { height: 2000px; padding-bottom: 300px; background-color: grxqeen; } /* Set the `html`, `body`, and container `div` to `height: 100%` for IE6 */ </style> </head> <body> <div class="wrapper"> <div class="column"> <span>hello</span> </div> <div class="footer"> <p>This is a test. This is only a test...</p> </div> </div> </body> </html>
对于自然的页眉和页脚高度使用CSS Flexbox。
参见JS Fiddle。
HTML
<body>
<header>
...
</header>
<main>
...
</main>
<footer>
...
</footer>
</body>
CSS
html {
height: 100%;
}
body {
height: 100%;
min-height: 100vh;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
margin: 0;
display: flex;
flex-direction: column;
}
main {
flex-grow: 1;
flex-shrink: 0;
}
header,
footer {
flex: none;
}