2

I have a container <div> which has a max-height property. This <div> contains another <div>, and I want the child <div> to grow to the maximum height of its container.

<div id='parent'>
  <div id='child'>
  </div>
</div>

This is easy enough when the parent <div> has a fixed height, but I cannot find a solution for making the child <div> assume the max-height of the container. There is no padding or margin or anything to worry about - I simply need the child <div> to assume the max-height of the parent.

How can I do this?

Owen
  • 75
  • 1
  • 8

3 Answers3

2

Set the parent's display property to flex, and the flex direction to column:

#parent {
  display: flex;
  flex-direction: column;
  max-height: 100px;
  border-bottom: 2px solid red; /** example - to show the effect on the parent **/
}

#child {
  height: 100vh;
  background: blue;
}
<div id="parent">
  <div id="child">
  </div>
</div>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Seems to work simply because the child div has a greater height than max-height, but flex container somehow clips the height without overflow. Odd behaviour, but thank you. – Owen May 30 '20 at 20:53
  • 1
    @Owen not odd but logical: https://stackoverflow.com/a/49492522/8620333 – Temani Afif May 30 '20 at 21:12
0

There are few things to note,
1. Height should be in vh to achieve responsiveness, better when dealing with height CSS
2. it's preferable to use vh as the unit for height.

.parent {
  max-height: 25vh;
  width: 15vw;
  background-color: aquamarine;
}

.child {
  background-color: brown;
  height: 25vh;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>

<div id='parent' class='parent'>
  <div id='child' class='child'>
  </div>
</div>

</body>

</html>
Aditya toke
  • 461
  • 4
  • 14
  • Thank you - but I don't know the max-height of the parent container in advance, so it's not quite as simple as synchronising the value of the child's height to the max-height of the container. – Owen May 30 '20 at 20:57
0

That is super simple to fix, simply add a height to your parent div.

<div class="parent">
  <div class="child"></div>
</div>
.parent{
  max-height:100px;
  width:500px;
  height:300px;
  background:coral;
}
.child{
  width:100%;
  height:100%;
  background:blue;
}