1

I have a div of height 100%. Inside that div, there are two children: an <a> and another <div>. The child <div> also has a height of 100%. I expected setting the child div's height to 100% would make it fill up the remaining height, not copy the height of the parent element and disregard fellow children leading to unintended overflow.

Example: https://codepen.io/gamepro5/pen/Jjpaqva (why is the child class in this example overflowing it's parent with a height of 100%?)

html {
  height: 100%;
}
a {
  display: block;
  text-align: center;
}
body {
  margin:0;
  width:100%;
  height: 100%;
}
.parent {
  width: 75%;
  background-color: red;
  height: 100%;
}
.child{
  height: 100%;
  width: 75%;
  background-color: green;
  /*would need to do a calc of 100% minus whatever the height of the <a> tag is, but that is annoying to do since the height of the other items can change. */
}
.child p {
  text-align: center;
}
<html>
  <body>
    <div class="parent">
      <a>Daddy Potato (king of all potatoes):</a>
      <div class="child"><p>Potatoe</p><p>Potatoe</p><p>Potato</p><p>Potate</p><p>Ube</p></div>
    </div>
  </body>
</html>

I simply want the child div to fill up the remaining available space with it's height without overflowing.

Gamepro5
  • 29
  • 3
  • 3
    `height:100%;` indeed means "same as the entire inner height of the container", regardless of sibling elements - that's how legacy CSS flow works. If you want a flexible layout that can be aware of the container and siblings and fill gaps in, you would have to use either a flex or a gird layout. – Noam Jun 08 '22 at 08:15

1 Answers1

0

You can achieve this with flex: Set display: flex and flex-flow: column; on the parent element, and on the child set flex-grow: 1;

html {
  height: 100%;
}
a {
  display: block;
  text-align: center;
}
body {
  margin:0;
  width:100%;
  height: 100%;
}
.parent {
  width: 75%;
  background-color: red;
  display: flex;
  flex-flow: column;

  height: 100%;
}
.child{
  flex-grow: 1;
  width: 75%;
  background-color: green;
}
.child p {
  text-align: center;
}
<html>
  <body>
    <div class="parent">
      <a>Daddy Potato (king of all potatoes):</a>
      <div class="child"><p>Potatoe</p><p>Potatoe</p><p>Potato</p><p>Potate</p><p>Ube</p></div>
    </div>
  </body>
</html>
Terminat
  • 1,199
  • 5
  • 21
  • If the child div is also a flexbox, when it comes time for that box to start wrapping the elements inside it, it will ignore your fix and use cause the same scrolling issue. It refuses to start wrapping when there is no space left with respect to the sibling. Instead, it only starts wrapping when the window is under 100% the height of it's parent. Any way to fix that if the child div is also display: flex;? – Gamepro5 Jun 08 '22 at 10:22
  • Simply by adding another wrapper, so your child will have a flex-grow, and the child of the child will have a display: flex; – Terminat Jun 08 '22 at 12:25