【问题标题】:Sticky footer with flexbox带有 flexbox 的粘性页脚
【发布时间】:2018-10-29 23:34:27
【问题描述】:

我发现了一种为我的网站创建粘性页脚的非常简单的方法,乍一看似乎效果很好。

但由于我没有看到其他人使用相同的东西,我想知道这种做法是否被打破,在根本不支持 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>

对于不知道 react 的人:外部 div 可以看作是“普通”html 页面上的 body 元素。

body-div 的 css:

min-height: 100vh;

所以基本上我让内部 div 和主页脚分别被推到顶部和底部,方法是将它们的容器设置为 flex-box,并将 justify-content 的属性设置为 space-between。

我还想补充一点,除了页脚之外,我网站的内容将进入内部 div。

【问题讨论】:

    标签: html css twitter-bootstrap react-native flexbox


    【解决方案1】:

    是的,这是正常设置。这就是 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; }
    <main>
      <article>inner div</article>
      <footer>footer</footer>
    </main>

    另外,如果您希望主要内容填充空白区域,同时将页脚固定在底部,您甚至不需要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; }
    <main>
      <article>inner div</article>
      <footer>footer</footer>
    </main>

    最后,当弹性容器中有多个元素时,justify-content 可能无法提供足够的对齐选项。 auto margins 让您拥有更多的灵活性。

    【讨论】:

      猜你喜欢
      • 2016-07-02
      • 2017-11-04
      • 2017-03-17
      • 2018-06-30
      • 2015-04-08
      • 2012-12-28
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多