div 内的垂直空间共享 (HTML)

问题描述 投票:0回答:1

我有一个最大高度为 80 rem 的父 div。我有 2 个没有固定高度的子 div(取决于里面的内容)。如果他们的身高都超过 40 rem,我希望他们共享 50-50 的空间。否则,将它们的最大高度设置为 70 rem。我怎样才能实现这个目标

尝试将它们的最大高度设置为 70,导致它们按预期溢出外部 div。将 max-heights 设置为 50 每个在空间利用率方面效率低下

html frontend web-frontend
1个回答
0
投票
You can use CSS Flexbox and JavaScript to achieve this behavior. CSS alone will not fix your problem. So JavaScript is necessary to adjust the heights dynamically.

Here is an example

    function adjustChildHeights() {
      const parent = document.querySelector('.parent');
      const child1 = document.querySelector('.child1');
      const child2 = document.querySelector('.child2');

      // Reset max-height to 70rem initially
      child1.style.maxHeight = '70rem';
      child2.style.maxHeight = '70rem';

      // Calculate total content height
      const child1ContentHeight = child1.scrollHeight;
      const child2ContentHeight = child2.scrollHeight;

      if (child1ContentHeight > 40 * 16 && child2ContentHeight > 40 * 16) {
        // If both exceed 40rem, set their heights to 50% each
        child1.style.maxHeight = 'none';
        child2.style.maxHeight = 'none';
        child1.style.flex = '1 1 50%';
        child2.style.flex = '1 1 50%';
      } else {
        // Otherwise, revert to initial max-heights
        child1.style.flex = '1 1 auto';
        child2.style.flex = '1 1 auto';
      }
    }

    // Adjust heights on DOM load and resize
    window.addEventListener('load', adjustChildHeights);
    window.addEventListener('resize', adjustChildHeights);
    .parent {
      max-height: 80rem;
      display: flex;
      flex-direction: column;
      overflow: hidden;
     background-color: DodgerBlue;
        
    }

    .child {
      flex: 1;
      overflow: auto; /* Ensures content scrolls if it exceeds the height */
      max-height: 70rem; /* Initial max-height */
      background-color: #f1f1f1;
      margin: 1px;

    }
    <div class="parent">
      <div class="child child1">
    Box 1, Lorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit.Lorem ipsum dolor sit amet, consectetur adipiscing elit.
      </div>
      <div class="child child2">
    Box 2
      </div>
    </div>
**JavaScript Adjustment:** The JavaScript function adjustChildHeights checks the content heights of both child divs. - If both exceed 40rem, it adjusts the flex property to ensure they take up 50% of the parent’s height each. - If either does not exceed 40rem, it sets the flex property back to auto and the max-height to 70rem.
© www.soinside.com 2019 - 2024. All rights reserved.