1

In the codepen I am trying to fill the height of parent if child height is less than the parent or overflow the children if their height exceeds that of the parent. But when I hardcode child height, I expect a scrollbar. But instead, the children are just filling the parent.

html,body{
  height:100%;
}
.grand-parent{
  height:100%;
  overflow:auto;
  display:flex;
}
.parent{
  display:flex;
  flex-direction:column;
  min-height:100%;
  width:300px;
}

.child{
  height:1500px;
  width:100%;
  display:flex;
}

.green{
  background:green;
}

.blue{
  background:blue;
}
<div class="grand-parent">
  <div class="parent">
    <div class="child green"></div>
    <div class="child blue"></div>
  </div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Flake
  • 1,386
  • 17
  • 31

2 Answers2

0

Try the code below.

html,body{
  height:100%;
  margin: 0;
}

.grand-parent{
  height:100%;
  overflow:auto;
}

.parent{
  display:flex;
  flex-direction:column;
  min-height: 100%;
  background:red;
}

.child{
  height:150px;
  width:100%;
  display:flex;
}

.green{
  background:green;
}

.blue{
  background:blue;
}
<div class="grand-parent">
 <div class="parent">
   <div class="child green"></div>
   <div class="child blue"></div>
 </div>
</div>

The mistake you did was, you added display: flex to .grand-parent and flex: 1 to the .parent. That means the .parent will adjust according to the height of .grand-parent. So I have removed that 2 properties from the style

Abin Thaha
  • 4,493
  • 3
  • 13
  • 41
  • what if the child height is less and I want it to fill the screen? I did try ur approach before posting. – Flake Aug 13 '18 at 06:39
  • You can give `min-height: 100%` to `.parent`. Please let me know if there is anything else – Abin Thaha Aug 13 '18 at 06:42
  • I have updated the code, it seems the child content is collapsing if I remove `flex:1`. – Flake Aug 13 '18 at 07:51
  • any idea why the parent height is 0. – Flake Aug 13 '18 at 07:52
  • I have updated the code as well. Check now. Currently, I have given the red color to the `.parent` and given `150px` height to each child. Increase the height and verify yourself – Abin Thaha Aug 13 '18 at 08:18
0

Don't use flex for the parent, instead set min-height: 50% for the child

html,
body {
  height: 100%;
}

.grand-parent {
  height: 100%;
  display: flex;
}

.parent {
  flex-grow: 1;
  overflow: auto;
}

.child {
  height: 1500px;
  width: 100%;
  display: flex;
  min-height: 50%;
}

.green {
  background: green;
}

.blue {
  background: blue;
}
<div class="grand-parent">
  <div class="parent">
    <div class="child green"></div>
    <div class="child blue"></div>
  </div>
</div>
Itay Gal
  • 10,706
  • 6
  • 36
  • 75