Prevent child div from expanding outside of parent?

Solution 1:

You can change your #insideDiv's max-height CSS property from 100% to inherit. So this rule will be like this:

max-height: inherit;

You also might want to add box-sizing:border-box; if you go this route, as that will allow any borders or padding on #insideDiv to behave as (probably) desired.


The cause of this issue is that max-height:100%; looks for the parent's height, not its max-height for how tall it's allowed to be. Thus, you end up with the classic non-deterministic relative height problem. If you give the parent a deterministic height (rather than max-height), 100% can resolve deterministically.

Solution 2:

Try this flexbox layout, it works fine with either fixed or percentage height / max-height.

jsFiddle

html, body {
  height: 100%;
  margin: 0;
}
#topDiv {
  background-color: lightblue;
  max-height: 50%;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
#insideDiv {
  background-color: pink;
  overflow-y: auto;
}
<div id="topDiv">
  <div>
    No scroll content
  </div>
  <div id="insideDiv">
    Some inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>More inside content
    <br>
  </div>
</div>

Solution 3:

You need to move overflow-y:auto; to #topDiv

You can then modify your max-height values to whatever you want for either and they will work as expected.