Task
In the block on the page, you need to place two nested blocks so that one block has the maximum height, and the second one takes up all the free space remaining in the parent block. 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.
To begin with, the task should be solved without regard to the content, i.e. with two empty child blocks:
How it works
The parent unit (shown in green in the picture) is set to
display: flex; and
flex-direction: column; to set the direction of content. The child blocks are styled
flex: 0 0 auto; for a block for which height is known, and
flex: 1 0 auto; for a block that butts to stretch to all 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, and since in this case, the less greedy is given a height (the maximum height can be set), the more greedy block takes up all the free space.
')
Add content to the bottom block
To add a scroll, it is enough to specify
overflow: auto;Add content to the top block.
It is as easy as with the lower unit, it will not work. This is because flex takes into account its height and content.
To solve this problem, the content must be
positioned absolutely (
position: absolute; ) and set the properties top, right, bottom, left to zero (to stretch it to the size of the block)
Now the block occupies the size we need, but the content gets out of it. To solve this problem, it is necessary to specify
position: relative; overflow: auto;Voila, we got two blocks with a scroll, one of which has a maximum height, and the second stretches across the free space.
Result (HTML):<div class="container"> <div class="first-child"> <div class="first-content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua </div> </div> <div class="second-child"> <div class="second-content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua </div> </div> </div>
Result (SCSS) .container { display: flex; flex-direction: column; width: 150px; height: 200px; background-color: #A5D6A7; .first-child { flex: 1 0 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: 0 0 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.