我正在使用这种方法将页脚保持在底部:https://codepen.io/cbracco/pen/zekgx
body {
position: relative;
padding-bottom: 6rem;
min-height: 100%;
}
.footer {
position: absolute;
bottom: 0;
}
问题是我们根据页面有几个不同的页脚版本,它们有不同的高度。
因此,在某些页面上,主内容底部和页脚之间存在太多死角。
我们可能会根据页面改变身体的底部填充,但考虑到我们网站的结构,这将不容易实现,它似乎不是一个非常优雅的修复。
答案 0 :(得分:2)
有几种CSS方法可以将页脚固定到容器的底部。
一种现代技术使用flexbox。使用flex属性,您可以:
html {
height: 100%;
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
display: flex; /* establish flex container */
flex-direction: column; /* align child elements ("flex items") vertically */
justify-content: space-between; /* pin both flex items to opposite ends */
margin: 0;
min-height: 100%;
font-family: "Helvetica Neue", Arial, sans-serif;
}
.demo {
margin: 0 auto;
padding-top: 64px;
max-width: 640px;
width: 94%;
}
.demo h1 {
margin-top: 0;
}
.footer {
padding: 1rem;
background-color: #efefef;
text-align: center;
}
<div class="demo">
<h1>CSS “Always on the bottom” Footer</h1>
<p>I often find myself designing a website where the footer must rest at the bottom of the page, even if the content above it is too short to push it to the bottom of the viewport naturally.</p>
<p>However, if the content is taller than the user’s viewport, then the footer should disappear from view as it would normally, resting at the bottom of the page (not fixed to the viewport).</p>
<p>If you know the height of the footer, then you should set it explicitly, and set the bottom padding of the footer’s parent element to be the same value (or larger if you want some spacing).</p>
<p>This is to prevent the footer from overlapping the content above it, since it is being removed from the document flow with <code>position: absolute;</code>.</p>
</div>
<div class="footer">This footer will always be positioned at the bottom of the page, but <strong>not fixed</strong>.</div>
注意:使用justify-content: space-between
时,可以将两个元素(如问题中的元素)固定到Flex容器的相对边缘。如果有两个以上的元素,则应使用auto
边距(more details)。
浏览器支持
所有主流浏览器except IE 8 & 9都支持Flexbox。最近的一些浏览器版本,例如Safari 8和IE10,需要vendor prefixes。要快速添加前缀,请使用Autoprefixer。 this answer中的更多详细信息。