How can I fit a scrollable body within a view port?
There is a header and a footer in this table with rows. Their height is based on the components inside. But I want the body to accommodate the rest of the space so that it takes the entire height of the view port.
const body = document.getElementById('body');
const createFakeData = (id) => {
const row = document.createElement('div')
row.innerHTML = "Row" + id;
row.classList.add('row')
body.appendChild(row);
}
for (let i = 0; i < 100; i++) {
createFakeData(i);
}
.row {
background-color: red;
padding: 10px;
margin: 0 0 5px 0;
}
.container {
height: 100vh;
}
.header {
height: 100px; /*Random value, height depends on components inside*/
background-color: yellow;
}
.body {
overflow-y: scroll;
/*height: something; Height should take the remaining space so everything fits view port*/
}
.footer {
height: 100px; /*Random value, height depends on components inside*/
background-color: orange;
}
<div class="container">
<div class="header">Header</div>
<div class="body" id="body"></div>
<div class="footer">Footer</div>
</div>
3
Answers
Just replace your css of body class with this :
The .container class is set to use flexbox layout. This allows you to create a flexible container where its child elements (header, body, and footer) can be controlled in terms of their sizing and alignment.
The .header and .footer classes have fixed heights, just as in your original code.
The .body class uses the flex property with a value of 1. This means it will take up the remaining available vertical space in the container. Additionally, overflow-y: auto is added to enable vertical scrolling if the content inside the body exceeds the available space.