html - 为什么关闭 1 像素边框会在固定位置标题和 Flex 增长的情况下产生 75 像素溢出?

标签 html css flexbox height border

对此感到困惑...我有以下布局:

  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    body {
      height: 100vh;
      border: 1px solid red;
    }
    header {
      position: fixed;
      max-width: 800px;
      height: 75px;
      top: 0;
      left: 0;
      right: 0;
      margin: 0 auto;
      background-color: beige;
    }
    main {
      display: flex;
      flex-direction: column;
      max-width: 800px;
      margin: 75px auto 0 auto;
      border: 1px solid green;
      height: calc(100% - 75px);
    }
    main section {
      background-color: rgb(206, 152, 114);
      flex: 1;
    }
    footer {
      background-color: rgb(245, 186, 36);
    }
  </style>

  <body>
    <header>header. position:fixed height:75x</header>
    <main>
      <section>flex grow section</section>
      <footer>footer</footer>
    </main>
  </body>
</html>

body 周围的边框显示它占据了整个视口(viewport)的高度。如果我在开发人员工具中关闭边框,则会出现一个垂直滚动条,并且折叠下方的标题看起来像固定高度。即使固定标题下方的 block 的 margin-top 为 75px,并且已从其高度中扣除了该值。

为什么注释掉主体周围的 1 像素边框会导致这种行为?

https://jsfiddle.net/karasutengu/r8awmpfz/4/

最佳答案

这是由于固定位置造成的。

我建议使用粘性 header 而不是固定 header 。因为你的 html 结构允许这样做。

粘性定位的情况下,您不必为各部分从顶部设置额外的边距,因为粘性元素充当相对元素。

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    height: 100vh;
    border: 1px solid red;
}

header {
    position: sticky;
    max-width: 800px;
    height: 75px;
    top: 0;
    /*left: 0;
    right: 0;*/
    margin: 0 auto;
    background-color: beige;
}

main {
    display: flex;
    flex-direction: column;
    max-width: 800px;
    /*margin: 75px auto 0 auto;*/
    margin: 0 auto 0 auto;
    border: 1px solid green;
    height: calc(100% - 75px);
}

main section {
    background-color: rgb(206, 152, 114);
    flex: 1;
}

footer {
    background-color: rgb(245, 186, 36);
}
<body>
    <header>header. position:fixed height:75x</header>
    <main>
        <section>flex grow section</section>
        <footer>footer</footer>
    </main>
</body>

关于html - 为什么关闭 1 像素边框会在固定位置标题和 Flex 增长的情况下产生 75 像素溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65987398/

相关文章:

html - 在我的页面顶部获得透明导航

React-Native:如何在没有明确宽度和高度的情况下填充全屏?

html - 减少或删除 MDL 文本字段的垂直填充

html - 部分内容在保留在其容器内时不会调整大小

html - 如何防止表体滚动条偏移表头列?

css - 如何为 IE8 添加边框半径和投影?

C# 发送带有 html 链接的电子邮件到文件 - 无法识别的转义序列

html - 放大下拉菜单中的 div

html - 动态布局的问题

css - Flexbox 垂直对齐到父元素的中间