对此感到困惑...我有以下布局:
<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 像素边框会导致这种行为?
最佳答案
这是由于固定位置造成的。
我建议使用粘性 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/