html - Flexbox 中元素之间的未知间隙

标签 html css flexbox

顶部的红色蓝色条之间有一个神秘的空间。

我做错了什么?当我删除 main 时,栏消失了。但是 footer 到了顶部?

我做了一个 fiddle :https://jsfiddle.net/v9yrmafw/1/#

.strip {
  height: 20px;
  background: red;
}
.bar {
  text-align: center;
  background: blue;
  color: white;
  height: 100px;
}
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.footer {
  margin-top: auto;
}
.footer__body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 70px;
  background: yellow;
  color: white;
}
main {
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: auto;
}
<div class="container">
  <main>
    <div class="strip"></div>
    <div class="bar">
      <h1>Home</h1>
    </div>
  </main>

  <footer>
    <div class="footer">
      <div class="footer__body">
        <p>© {{ copyright }} {{ now }}</p>
      </div>
    </div>
  </footer>
</div>

最佳答案

这是由于 margin collapsing 而发生的h1bar div - 所以你可以:

  1. h1

    的 margin 重置为零
  2. bar

    添加填充/边框

请参阅下面的演示 - 我在 bar 中添加了一些填充:

.strip {
  height: 20px;
  background: red;
}
.bar {
  text-align: center;
  background: blue;
  color: white;
  height: 100px;
  padding: 10px;
}
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.footer {
  margin-top: auto;
}
.footer__body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 70px;
  background: yellow;
  color: white;
}
main {
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: auto;
}
<div class="container">
  <main>
    <div class="strip"></div>
    <div class="bar">
      <h1>Home</h1>
    </div>
  </main>

  <footer>
    <div class="footer">
      <div class="footer__body">
        <p>© {{ copyright }} {{ now }}</p>
      </div>
    </div>
  </footer>
</div>

关于html - Flexbox 中元素之间的未知间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41019889/

相关文章:

javascript - 如何使用 jQuery 替换网站上的广告?

javascript - 如何使用 D3 库制作响应式 Canvas 动画

html - 具有 3 个 div 的容器,使用 Flex-box/Grid

javascript - 单元格的动态宽度 React Native

css - flexbox 元素的宽度被忽略

当我执行这个 go 代码时,html 代码显示没有 css,但是当我直接在浏览器中打开它时,它显示 html 和 css 都很好

html - 非 JS youtube 弹出窗口(纯 html?)

javascript - 显示 angular-loading-bar 并禁用页面的所有内容,直到页面加载

javascript - jquery.append() - 仅附加列表的最后一个元素,前面的元素被删除

jquery - 悬停在 div 上的效果同时悬停在整个标签上