Search code examples
htmlcssflexboxoverflow

How can I make a div grow to fit its content, up to the max size of the parent container?


I'm positioning a modal div in the middle of the page with a max-height defined as a % of its container, in this case it shouldn't exceed 70% of the page height.

The contents of the div are two elements:

  • A fixed height header div
  • And a variable height content div

I want the modal to grow with the content until the max-height, then the content div should start scrolling. However whatever I do, the content seems to spill out of the modal like so:

enter image description here

This is my markup and styling:

body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal {
  max-height: 70%;
  border: 5px dashed green;
  border-radius: 5px;
}

.container {
  /* I cannot remove this container */
  display: flex;
  flex-direction: column;
  width: 600px;
}

.header {
  flex: none;
  background: red;
  height: 100px;
}

.content {
  flex: 1;
  background: yellow;
  overflow: auto;
}

.big-stuff {
  margin: 10px;
  background: orange;
  height: 600px;
}
<div class="modal">
  <div class="container">
    <div class="header">
      Header
    </div>
    <div class="content">
      Content. Should shrink or grow to fit content but only to a max of the container height
      <div class="big-stuff">
        Large content
      </div>
    </div>
  </div>
</div>

Unfortunately I can't change the markup so I'm trying to get this working just by modifying CSS. If I remove the .container div, then everything seems to work but I was hoping there was another way.

Full example available here: https://codepen.io/dyancat/pen/QWaOGpB


Solution

  • You can add flex to the modal, so that the content will not expand out of its parent (modal in this example):

    .modal {
        max-height: 70%;
        border: 5px dashed green;
        border-radius: 5px;
        display: flex; /* Add this flex */
    }