为什么关闭一个1像素的边框会创建一个75px的溢出与固定位置的头和flex增长?



对此感到困惑…我有如下的布局:

<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>

正文周围的边框显示它占用了整个视口高度。如果我在开发人员工具中关闭边框,就会出现一个垂直的滚动条,看起来就像固定高度的页眉在折叠栏下面。尽管固定标题下面的块的margin-top为75px,并且已经从它的高度中扣除了这个值。

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

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

这是由于固定位置。

我建议使用粘贴header代替固定header。因为你的html结构允许。

对于sticky定位,你不需要设置额外的空白从顶部的部分,因为粘性元素作为一个相对.

* {
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>

最新更新