Home > database >  Set the grid container height as two child items
Set the grid container height as two child items

Time:09-13

Is there a chance I can set the grid container's height equal to two grid items using CSS? The attached picture shows the expected result of having the rest of the content set as an overflow scroll.

PS. This shall also be responsive and adjust if the grid container's children's height changes.

enter image description here

CodePudding user response:

You have to use Javascript for this. Capture the height using the getBoundingClientRect() and the container margin using getComputedStyle(). You have to be a little bit careful how you style the parent and children elements and also be aware of collapsing margins if you use margin-top and margin-bottom. We can then use a CSS variable to store the result and that will then affect the container height rule. We attach the function to the window resize event and also fire it on initial window load. Here's an example to get you started and tweak to suit your needs.

window.onload = () => {
  window.onresize = (event) => {
    resizeContainer();
  };
  resizeContainer();
}

function resizeContainer() {
  const container = document.querySelector('.container');
  const containerStyle = window.getComputedStyle(container);
  const containerPaddingTop = parseInt(containerStyle.getPropertyValue('padding-top'));
  const containerPaddingBottom = parseInt(containerStyle.getPropertyValue('padding-bottom'));
  const child1 = document.querySelector('.container > div:first-child');
  const child2 = document.querySelector('.container > div:nth-child(2)');
  const height = getOverallHeight(child1)   getOverallHeight(child2)   containerPaddingTop   containerPaddingBottom;
  container.style.cssText = "--container-height:"   height   "px";
}

function getOverallHeight(element) {
  const height = element.getBoundingClientRect().height;
  const style = window.getComputedStyle(element);
  const marginTop = parseInt(style.getPropertyValue('margin-top'));
  const marginBottom = parseInt(style.getPropertyValue('margin-bottom'));
  return height   marginTop   marginBottom;
}
* {
  box-sizing: border-box;
}

.container {
  overflow-y: auto;
  height: var(--container-height);
  border: 2px solid black;
  padding: 0.5rem;
}

.container>div {
  border: 2px solid red;
  margin-top: 0.25rem;
  min-height: 5rem;
}
<div  style="--container-height:1rem;">
  <div>
    Consectetur ea veniam dolore cillum occaecat. Pariatur occaecat esse eiusmod mollit commodo aliqua. Ad veniam aliquip adipisicing fugiat aliquip do minim ad fugiat cillum sunt. Cillum et commodo occaecat ullamco do occaecat sint irure esse fugiat voluptate
    commodo excepteur. Irure nisi ut qui fugiat non quis occaecat nisi mollit do fugiat.
  </div>
  <div>
  </div>
  <div>
  </div>
  <div>
  </div>
</div>

  • Related