Rik*_*eek 6 html css flexbox twitter-bootstrap react-native
我发现了一种为我的网站创建粘性页脚的非常简单的方法,乍一看,它似乎工作得很好。
但是因为我没有看到其他人使用同样的东西,所以我想知道这种做法是否在根本不支持 flex-box 的浏览器之外被打破了?
我使用 bootstrap 来设置 flex-box,我在 React 中工作,这是我的代码:
<div className="body-div d-flex flex-column justify-content-between">
<div> <!-- inner div -->
<MainNav/>
</div>
<MainFooter className="d-flex flex-column"/>
</div>
Run Code Online (Sandbox Code Playgroud)
对于不知道 react 的人:可以将外部 div 视为“正常”html 页面上的 body 元素。
body-div的css:
min-height: 100vh;
Run Code Online (Sandbox Code Playgroud)
所以基本上我通过将它们的容器设置为 flex-box 并将 justify-content 的属性设置为 space-between 来分别将内部 div 和主页脚推到顶部和底部。
另外我想补充一点,我网站的内容,除了页脚,将进入内部 div。
是的,这是正常的设置。这justify-content: space-between就是应该做的:将第一个和最后一个元素固定到容器的边缘。
main {
display: flex;
flex-direction: column;
justify-content: space-between;
height: 100vh;
}
article { background-color: lightgreen; }
footer { background-color: orangered; }
body { margin: 0; }Run Code Online (Sandbox Code Playgroud)
<main>
<article>inner div</article>
<footer>footer</footer>
</main>Run Code Online (Sandbox Code Playgroud)
此外,如果您希望主要内容填充空白空间,同时将页脚固定到底部,您甚至不需要justify-content. 使用flex-grow.
main {
display: flex;
flex-direction: column;
height: 100vh;
}
article {
flex-grow: 1;
background-color: lightgreen;
}
footer { background-color: orangered; }
body { margin: 0; }Run Code Online (Sandbox Code Playgroud)
<main>
<article>inner div</article>
<footer>footer</footer>
</main>Run Code Online (Sandbox Code Playgroud)
最后,当您在一个 flex 容器中有多个元素时,justify-content可能无法提供足够的对齐选项。自动边距具有更大的灵活性。