我已将页脚 DIV 固定到视口(viewport)底部,如下所示:
#Footer
{
position: fixed;
bottom: 0;
}
如果页面上没有太多内容,此方法效果很好。但是,如果内容填满页面的整个高度(即垂直滚动条可见),页脚会与内容重叠,我不会这样做。
如何让页脚贴在视口(viewport)的底部,但不与内容重叠?
最佳答案
现代“粘性页脚”解决方案将使用 flexbox .
tl;dr::将容器(主体)设置为 display:flex;flex-direction:column
和您要向下移动到 margin-top:auto
的子项(页脚) .
首先,我们将主体设置为垂直“flex ”其元素,确保其高度为 100%。
然后我们设置flex: 0 0 50px
在页脚元素上,这意味着:“不增长,不收缩,高度为 50px”。事实上,我们可以省略 flex
完全属性并与 height:50px
一起使用.
我们可以设置display:flex
在类似 <body>
的事情上本身有点鲁莽,因为 flex 容器的子容器有一个隐式值 flex: 0 1 auto
(又名 flex:initial
)如果省略,则(几乎)等同于 flex:none
(这是简写
flex:0 0 auto
):
The item is sized according to its width and height properties. It shrinks to its minimum size to fit the container, but does not grow to absorb any extra free space in the flex container.(MDN)
就粘性部分而言,它是 margin-top:auto
在给我们想要的东西的页脚上。在 flex 容器中应用,自动边距具有新的含义,而不是通常的“获得等量的可用空间”,它们意味着“吸收所有可用的可用空间”。
来自规范(8.1. Aligning with auto margins):
Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.
陈述更多simply :
If you apply auto margins to a flex item, that item will automatically extend its specified margin to occupy the extra space in the flex container
旁白:“正常”的 flexbox 布局方法可能是 flex 中间部分 ala <div id="main>...</div>
垂直到 100%,这也会使页脚“粘”在底部。这种方法向我们展示了灵活的盒子模型实际上足够灵活,可以让我们调整/移动孤立的元素。
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
#footer {
background-color: #efefef;
flex: 0 0 50px;/*or just height:50px;*/
margin-top: auto;
}
<p>we've assumed only that there's random space-taking content above the footer...</p>
<p>lorem ipsum dolor flex...</p>
<div>
<p>random content.</p><p>random content.</p><p>random content.</p><p>random content.</p>
</div>
<div id="footer">FOOTER</div>
关于html - 防止固定页脚重叠内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2744690/