position:absolute;
left:0;
bottom:0;
right:0;
对于容器(即react-root div):
padding-bottom:60px;
作为另一种选择(如果您不需要支持IE 8),您可以尝试在height: calc(100% - 60px);
如果上述解决方案对某些人无效,您可以尝试以下步骤:
div
设置非静态position
,例如relative
(请记住默认的position
是static
)。100vh
;这使它可以在垂直方向上占用所有可用空间。div
中,则给它以下属性:position: absolute; bottom: 0; width: 100%
。更新:在某些情况下,将页脚div
的position
设置为absolute
可能无法正常工作。在这种情况下,请改用relative
。
希望以上步骤可以解决问题 :-)
我认为大家都忽略了一个技巧,就是在React中,在html和body元素之后,还有一个带有#root的div,它包括了整个内容。请参考下面的图片。
因此,需要将所有三个元素即html、body和#root的高度设置为100%。
html, body, #root {
height: 100%;
}
然后在 #root 中添加以下属性:
#root {
display: flex;
flex-direction: column;
}
你可能会想知道为什么需要将 #root 设置为 flex,而不是 body。原因是它是 footer 的最近父元素。
现在,只需对 footer 进行以下操作:
footer: { margin-top: auto }
position: fixed;
left:0;
bottom:0;
right:0;
即使可以使用 position: absolute
,但它不支持滚动。
在IT技术中,拥有内容包装器并将其最小高度设置为100vh非常重要:
min-height: 100vh; (100% of the viewport height)
min-height: 100%; (100% of the parent's element height)
看这里讲解得非常清楚,对我很有用:https://medium.com/@zerox/keep-that-damn-footer-at-the-bottom-c7a921cb9551
虽然来晚了,但我的解决方案是:
<div className="layout">
<Navbar />
<main>
{children}
</main>
<Footer />
</div>
.layout {
min-height: 100vh;
display: flex;
flex-direction: column;
}
.layout main {
flex-grow: 1;
}
您是否想要一个页面包装器,以便可以将页脚绝对定位在底部?如果是这样,您可以创建一个具有相对位置的新组件,并将其他内容作为子元素传递,并将页脚设置为底部的绝对定位。
希望我早点看到这个。这里是Ikechuk的答案片段,注意现在footer
也尊重边距(这可能不在上面的其他答案中):
html, body, div{
height:100%;
width:100%
display:block;
}
footer{
position:absolute;
bottom:0;
display:block;
width:100%
}
hr{
display: block;
unicode-bidi: isolate;
margin-block-start: 0.5em;
margin-block-end: 0.5em;
margin-inline-start: auto;
margin-inline-end: auto;
overflow: hidden;
border-style: inset;
border-width: 1px;
}
<html>
<body>
<div style={"margin=5%;"}>
<div style={"position:relative"}>
<footer>
<hr>
I am footer
</footer>
</div>
</div>
</body>
</html>
谢谢,@mwoelk已经回答了这个问题。我只是想对初学者更清楚地解释一下。
步骤1 --- 底部 CSS:
.Footer {
position: fixed;
left: 0;
bottom: 0;
right: 0;
}
步骤 2 --- Footer css的包装器: (让我们以React为例,通常将Footer包装在.App内。添加底部填充的原因是,如果内容太长,则避免一些内容被底部的Footer覆盖。)
.App {
padding-bottom: 60px;
}
.c-mt-auto {
margin-top: auto;
}
.c-container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
html,body { height: 100% }
。 - ctrlplusb<div id="bms-root">
的height
和/或min-height
设置为100%,但结果相同。 - An Nguyen