Perplexed by this...I have the following layout:
<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>
The border around the body shows it taking the full viewport height. If I toggle the border off in developer tools, a vertical scrollbar appears and I have what looks like the fixed height of the header below the fold. Even though the block below the fixed header has a margin-top of 75px and has deducted this from its height.
Why would commenting out the 1 pixel border around the body result in this behavior??
This is due to the fixed position.
I recommend using a sticky header
instead of a fixed header
. Because your html structure allows it.
In the case of sticky positioning, you don't have to set extra margin from the top for the sections, since the sticky element acts as a relative.
* {
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>