Instead of using min-height, we use height on the html element. Then we add min-height: 0 to the body element which is the trickiest part here. CSS grid (and also Flexbox) define a default min-height (and min-width) to child items as we can read in the specification:
To provide a more reasonable default minimum size for grid items, the used value of its automatic minimum size in a given axis is the content-based minimum size if all of the following are true: It is not a scroll container It spans at least one track in that axis whose min track sizing function is auto If it spans more than one track in that axis, none of those tracks are flexible Otherwise, the automatic minimum size is zero, as usual.
I know, the above is not intuitive and difficult to understand but always keep in mind this trick. You may need to add min-height: 0 or min-width: 0 in some cases where you face a strange overflow issue or you want an element to collapse/shrink even if it has a lot of content.
Finally, we add overflow: auto to the main element and we have another configuration where the footer is always visible and we can scroll the main content.
html {
display: grid;
height: 100%;
}
body {
display: grid;
min-height: 0;
grid-template-rows: auto 1fr auto;
}
main {
overflow: auto;
}
Worth noting that even using this configuration we can keep the default body margin. No more headaches trying to remove that extra margin coming from nowhere!
Now let’s add a sidebar to our layout. In addition to the three rows, we will have two columns.
html {
display: grid;
height: 100%; /* OR min-height: 100% */
}
body {
display: grid;
min-height: 0;
grid-template-rows: auto 1fr auto;
grid-template-columns: 200px 1fr; /* 2 columns */
}
header,
footer {
grid-column: 1/-1; /* header and footer takes both columns */
}
main {
overflow: auto;
}
I used 200px to set the width of the sidebar but you can also use a percentage value or even auto.
We need to make the header and the footer span both columns using grid-column: 1/-1 which means starting at the first column and ending at the last one.