我一直在使用 Flexbox 尝试制作粘性页脚,但出于某种原因,我的一个 div 与页脚重叠?当我将窗口拖动到更大的监视器时,页脚非常完美。我究竟做错了什么?

另外,我更愿意使用这种方法而不是其他方法,例如 table 方法。

这是我的 Html 布局:

<body>
    <div class="mainContent">...</div>
    <div class="footer">...</div>
</body>

在我的里面 mainContent div 我拥有网站的完整顶部部分,包括标题。我只需要使用它作为整个内容,然后有我的页脚。

这是我的CSS:

body
{
    height: 100%;
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    min-height: 100vh;
}

.mainContent
{
    -webkit-box-flex: 1;
    -ms-flex: 1;
    flex: 1;
    -webkit-flex: 1;
}

.footer
{
    height: 75px; 
    background: #222;
    color:#EEE;
}

我什至尝试过这个: http://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/

但我遇到了与我目前遇到的问题相同的问题。

更新

根据评论中的要求,我将主要内容 div 设置为 overflow: auto; 但我的内容被页脚掩盖了。我该如何解决这个问题?

有帮助吗?

解决方案

您需要在 css 中添加更多规则才能获得您想要的结果。就现在而言,它基本上是在说明当空间减少时,您的主要内容应该占用更多空间。因此,页脚并没有真正重叠,而是尺寸减小了。

这是我几个月前做的事情......css 中的很多规则都是遗留的,所以要小心,但我相信它接近你的目标:http://plnkr.co/edit/o2BAwvg3XV4YjwAwwmYR?p=preview

但我真的鼓励你使用它来创建你的 flex css 规则:http://the-echoplex.net/flexyboxes/

其他提示

我之前花了很多时间找到了使用 CSS3 Flexbox 或 Grid 来解决这个问题的快速而强大的解决方案。我希望这有帮助。

<body>
  <header></header>
  <main></main>
  <footer></footer>
</body>

这应该适用于 IE 和 Chrome:

body {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

main {
  flex: 1 0 auto;
}

footer, header {
    flex-shrink: 0;
}

您还可以尝试网格布局

html {
  height: 100%;
}

body {
  min-height: 100%;
  display: grid;
  grid-template-rows: 1fr 1fr auto;
}

footer {
  grid-row: 3/4;
}

参考我的网站: http://matthiassommer.it/web/javascript/sticky-footer-css3-flexbox-grid/

我知道答案已被接受,但我这里有一个非常简单的示例,仅使用您需要的代码(以及一些用于演示的 javascript)。

https://codepen.io/alexmccabe/pen/RgMBjJ

这是正在发生的事情:

首先你设置 bodyhtml 到浏览器高度的 100%。

html,
body { height: 100%; }

然后您设置一个包装元素以具有 min-height 100%,并显示 flex。该列可确保元素不会彼此相邻放置。

.site-wrapper {
    display: flex;
    flex-direction: column;
    min-height: 100%;
}

现在页脚变得 margin-topauto. 。它位于浏览器窗口的底部。

.site-footer {
    margin-top: auto;
}

笔记:确保包含所有旧的浏览器样式,并留意 Safari 8。有时这可能是一个棘手的问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top