带有 flexbox 的粘性页脚 [英] Sticky footer with flexbox
问题描述
我发现了一种为我的网站创建粘性页脚的非常简单的方法,乍一看似乎效果很好.
但由于我没有看到其他人使用同样的东西,我想知道这种做法是否被打破,在完全不支持 flex-box 的浏览器之外?
我使用 bootstrap 来设置 flex-box,我在 React 中工作,这是我的代码:
<div><!-- 内部 div --><主导航/><MainFooter className="d-flex flex-column"/>
对于不知道 react 的人:外部 div 可以被视为普通"html 页面上的 body 元素.
body-div 的css:
min-height: 100vh;
所以基本上我通过将它们的容器设置为 flex-box 并将 justify-content 的属性设置为 space-between 来分别将内部 div 和主页脚推到顶部和底部.
另外,我想补充一点,除了页脚之外,我网站的内容将进入内部 div.
是的,这是一个正常的设置.这就是 justify-content: space-between
应该做的:将第一个和最后一个元素固定到容器的边缘.
main {显示:弹性;弹性方向:列;对齐内容:间隔;高度:100vh;}文章 { 背景颜色:浅绿色;}页脚 { 背景颜色:橙红色;}正文{边距:0;}
<article>内部 div</article><footer>footer</footer></main>
此外,如果您希望主要内容填充空白空间,同时将页脚固定在底部,您甚至不需要 justify-content
.使用 flex-grow
.
main {显示:弹性;弹性方向:列;高度:100vh;}文章 {弹性增长:1;背景颜色:浅绿色;}页脚 { 背景颜色:橙红色;}正文{边距:0;}
<article>内部 div</article><footer>footer</footer></main>
最后,当您在一个 flex 容器中有多个元素时,justify-content
可能无法提供足够的对齐选项.使用自动边距,您可以获得更大的灵活性.
I found out a very simple way of creating a sticky footer for my website, and at first sight it seems to work perfectly.
But since I don't see other people using the same thing, I am wondering if this way of doing it is broken, outside of browsers which don't support flex-box at all?
I use bootstrap for setting flex-box, and I am working within React, here is my code:
<div className="body-div d-flex flex-column justify-content-between">
<div> <!-- inner div -->
<MainNav/>
</div>
<MainFooter className="d-flex flex-column"/>
</div>
For people who don't know react: the outer div can be seen as the body element on a 'normal' html page.
css for the body-div:
min-height: 100vh;
So basically I let the inner div and the main footer be pushed to the top and bottom respectively by setting their container to flex-box with the property of justify-content set to space-between.
Also I'd like to add that my site's content, except for the footer that is, will go inside the inner div.
Yes, this is a normal set-up. That's what justify-content: space-between
is supposed to do: Pin the first and last elements to the edges of the container.
main {
display: flex;
flex-direction: column;
justify-content: space-between;
height: 100vh;
}
article { background-color: lightgreen; }
footer { background-color: orangered; }
body { margin: 0; }
<main>
<article>inner div</article>
<footer>footer</footer>
</main>
Also, if you want the main content to fill the empty space, while pinning the footer to the bottom, you don't even need justify-content
. Use flex-grow
.
main {
display: flex;
flex-direction: column;
height: 100vh;
}
article {
flex-grow: 1;
background-color: lightgreen;
}
footer { background-color: orangered; }
body { margin: 0; }
<main>
<article>inner div</article>
<footer>footer</footer>
</main>
Lastly, when you have multiple elements in a flex container, justify-content
may not provide enough options for alignment. You have a lot more flexibility with auto margins.
这篇关于带有 flexbox 的粘性页脚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!