Assuming I have I have a header, main-content, and footer as the only direct children of the body.
I want to always fill the entire viewport, and if the total height is < 100vh, I want main#main-content to expand to fill the viewport. If I knew the header and footer would always be the same height, it’d be easy (#main-content {min-height:calc(100vh - 160px)}
But if the header and footer might vary in height (say some of the header content wraps as the viewport gets smaller), what’s the best way to do this?
I could do it with Javascript and just measure the height of the footer/header on page load, and on window resize, but is there a way to do this in CSS?
html,
body {
margin: 0;
padding: 0;
}
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1 0 0;
}
header,
footer,
main {
padding: 10px;
background: cyan;
border: 1px solid red;
}
main {
background: aquamarine;
}
The 2 key points are the min-height:100vh in the body and the flex:1 0 0 for main which makes the main element stretch between the header and footer no matter what the size the header and footer are.
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1 0 0;
}