Home > Enterprise >  Adjust div height to max n amount of child items
Adjust div height to max n amount of child items

Time:11-05

I have a div without height, whenever I add items then the height of div increases. However I want to limit the max height to 5 of child divs. Sometimes item have one or two line of text and should be treated as one item. When there is 6th item to appear, then scrollbar should appear in the div and height of the div should be adjusted to 5 items inside.

.box {
  border: 1px solid black;
  display: inline-block;
  width: 150px;
}
<div >
  <p >
  1 test
  </p>
    <p >
   2test test    test test    test test
  </p>
    <p >
   3test
  </p>
    <p >
   4test
  </p>
    <p >
   5 test
  </p>
  <p >
   6 test
  </p>
</div>

CodePudding user response:

Just based on the information given, you could loop through the first 5 items and get their heights using the getComputedStyle() method.

There is a somewhat weird behavior with margin collapsing, which could cause issues depending on how you implement this code. However based on the example provided this works as intended.

const box = document.querySelector(".box")
let maxHeight = 0

document.querySelectorAll(".item").forEach((item, index) => {
  if(index < 5) maxHeight  = parseFloat(getComputedStyle(item).getPropertyValue('height'))   parseFloat(getComputedStyle(item).getPropertyValue('margin-top'))
})

box.style.maxHeight = `${maxHeight}px`
.box {
  border: 1px solid black;
  display: inline-block;
  width: 150px;
  overflow: auto;
}
<div >
  <p >1 test</p>
  <p >2test test    test test    test test</p>
  <p >3test</p>
  <p >4test</p>
  <p >5 test</p>
  <p >6 test</p>
</div>

  • Related