Home > Back-end >  How to prevent an element from growing outside of its grandparent's boundaries?
How to prevent an element from growing outside of its grandparent's boundaries?

Time:05-20

I've seen a similar question answered when the element was a direct child of the container with the max-width set, but in my case, I have a div with dynamic content, and inside of it is another div, which is a growing list. I need this internal div to grow until the root div reaches its max-height, then switch to overflow.

html,
body {
  height: 100%;
}

#topDiv {
  background-color: lightblue;
  max-height: 150px;
  width: 100%;
  padding: 10px;
}

#insideDiv {
  background-color: pink;
  max-height: inherit;
  overflow-y:auto;
}

#anotherdiv {
  max-height: inherit;
}
<div id="topDiv">
  <p>
  First paragraph
  </p>
  <div id="anotherdiv">
   <div id="insideDiv">
    Some inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br>
  </div>
  </div>
  <p>
   Final paragraph
  </p>
</div>

CodePudding user response:

You could simply add overflow-y: auto to #topDiv.

html,
body {
  height: 100%;
}

#topDiv {
  background-color: lightblue;
  max-height: 150px;
  width: 100%;
  padding: 10px;
  overflow-y: auto;
}

#insideDiv {
  background-color: pink;
  max-height: inherit;
  overflow-y: auto;
}

#anotherdiv {
  max-height: inherit;
}
<div id="topDiv">
  <p>
    First paragraph
  </p>
  <div id="anotherdiv">
    <div id="insideDiv">
      Some inside content
      <br> More inside content
      <br> More inside content
      <br> More inside content
      <br> More inside content
      <br> More inside content
      <br> More inside content
      <br> More inside content
      <br> More inside content
      <br> More inside content
      <br>
    </div>
  </div>
  <p>
    Final paragraph
  </p>
</div>

CodePudding user response:

For this to work, you could set that max-height on #insideDiv instead of #topDiv.

html,
body {
  height: 100%;
}

#topDiv {
  background-color: lightblue;
  width: 100%;
  padding: 10px;
}

#insideDiv {
  background-color: pink;
  max-height: inherit;
  overflow-y:auto;
  max-height: 150px;
}

#anotherdiv {
  max-height: inherit;
}
<div id="topDiv">
  <p>
  First paragraph
  </p>
  <div id="anotherdiv">
   <div id="insideDiv">
    Some inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br> More inside content
    <br>
  </div>
  </div>
  <p>
   Final paragraph
  </p>
</div>

CodePudding user response:

#anotherdiv {
  max-height: 400px;
 overflow-y: auto;
}
  •  Tags:  
  • css
  • Related