In the following code I notice the last row overflow the parent container. I have tried to use overflow: auto;
but this adds scrollbars. How can I avoid the overflow?
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css">
<style>
#a { height: 33%}
#b { height: 17%}
#c { height: 50%}
</style>
<div class="container border border-warning" style="height: 400px">
<div id="a" class="row bg-primary m-2">A</div>
<div id="b" class="row bg-secondary m-2">B</div>
<div id="c" class="row bg-info m-2">C</div>
</div>
6
Answers
Simply make the container a flex container and you will have the shrink effect that will fix the issue. Then adjust the margin of the middle one to keep the same spacing like when you had margin-collapsing (flexbox disable margin-collapsing).
You can use
display:flex
. adddisplay: flex; flex-direction: column;
to the parent style.Or you can use
calc
to reduce themargin
from theheight
–Add the overflow property on the parent element.
Check documentation on : CSS overflow property
It is because there is a margin on A,B,C (because of m-2), and the full height of the 3 divs is 100% + 4*8px, more than the height of the container.
So you have to change the height of the container for
auto
if its not important to be 400px. (It would be 432 px.)Or
You have to remove m-2 and change the
margin
topadding: .5rem
and addbox-sizing: border-box
to A,B,C if the padding between the divs and the height ratio is important.Or
Add
overflow: hidden
to the container, so the last divs overflow wont be visible, but in that case the#c { height: 50%}
wouldn’t be true.The div boxes do not fit into the parent div box because of the margin space below each child div. The margin space below the divs is 8px. Total space occupied by margin is 32px which is 8% of the total space. So you must reduce the percentage height of each child div by 8/3px which is around 2px from each and 1px from any 2 of the divs.