Using CSS Flexbox to Position Blocks on a Page
Task
In a block on a page, it is required to place two nested blocks so that one block has a maximum height, and the second one takes up all the remaining free space in the parent block in height. Moreover, if the content does not fit in the block, add a scroll to it.
Implementation
When implementing this task, it was decided to use CSS Flexbox.
First you need to solve the problem without regard to content, i.e. with two empty child blocks:
How it works
The parent block (shown in green in the figure) is set to display: flex; and flex-direction: column; to set the direction of the content. The child blocks are given flex styles : 0 0 auto; for the block for which the height is known, and flex: 1 0 auto; for the block, which is butted to stretch all the free space. “1” for the second block in this case means “greed”, i.e. a more greedy block takes up more space than a less greedy one, because in this case, the less greedy is set to the height (the maximum height can be set), then the more greedy block takes up all the free space.
Add content to the bottom block
To add a scroll, just specify overflow: auto;
Add content to the top block
It’s as simple as with the bottom block, it won’t work out. That's because flex takes it into account and the height of the content.
To solve this problem, the content must be absolutely positioned ( position: absolute; ) and set its top, right, bottom, left properties to zero (to stretch it to fit the block)
Now the block takes the size we need, but the content climbs out of it. To solve this problem, you need to set position: relative; overflow: auto;
Voila, we got two blocks with a scroll, one of which has a maximum height, and the second is stretched across the entire free space.
<divclass="container"><divclass="first-child"><divclass="first-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
</div></div><divclass="second-child"><divclass="second-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
</div></div></div>.container {
display: flex;
flex-direction: column;
width: 150px;
height: 200px;
background-color: #A5D6A7;
.first-child {
flex: 10 auto;
position: relative;
overflow: auto;
width: 125px;
box-sizing: border-box;
background-color: #90CAF9;
.first-content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
padding: 5px;
}
}
.second-child {
flex: 00 auto;
width: 125px;
max-height: 75px;
padding: 5px;
box-sizing: border-box;
overflow: auto;
background-color: #CE93D8;
}
}
PS A working example can be found here.