Home > Software engineering >  How to expand a div to its parent's max-height
How to expand a div to its parent's max-height

Time:01-05

I'm working with an angular dialog layout in which the API to open and manage the dialog comes from a different library. When rendering, the dialog's parent container has a max-height attribute so the dialog's height is determined by the content's height (The dialog's parent container is managed by the library. I just have to supply the child component). So if I put an empty div, the dialog's height is 0 because there's nothing inside the div. How can I make the empty div expand to the max-height of the parent container?

To make this a bit more clear, I've isolated the scenario with an example-

HTML

<html>
<head>
</head>
<body>
<div >
  <div >
  </div>
</div>
</body>
</html>

CSS

.parent {
  background-color: purple;
  max-height: 100px;
}

.a {
  background-color: red;
}

Here I want the child to expand to its parent's max-height (i.e. 100px). I've tried using display: flex on parent and flex: 1 on the child but it didn't work. Note that I cannot just directly set the child's height to 100px because this 100px in my specific example is coming from a different library and I cannot assume it to remain constant.

CodePudding user response:

You can set the child max height to inherit (so you don't nee to know the value that was set in the parent).

And then you can set the height to something enormous. In your example 100% would do, but that relies on knowing the various positioning of ancestor elements so this snippet puts in something that is likely to be larger than the inherited max-height just as a demo.

<html>

<head>
  <style>
    .parent {
      background-color: purple;
      max-height: 100px;
    }
    
    .child {
      background-color: red;
      max-height: inherit;
      height: 10000px;
    }
  </style>
</head>

<body>
  <div >
    <div >
    </div>
  </div>
</body>

</html>

If you inspect computed styles in your browser dev tools you can see the computed value of the child height is 100px which is what you want.

CodePudding user response:

.parent {
      background-color: purple;
      max-height: 100px;
      overflow: auto;
    }
  •  Tags:  
  • Related