Select Page
JavaScript to equalize element heights
JavaScript to equalize element heights

To achieve equal heights for child elements with the class equalize within a parent element with the class equalize-columns, you can use CSS and possibly a bit of JavaScript. One common approach is using Flexbox or Grid layout along with JavaScript to calculate and set the heights dynamically.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .equalize-columns {
      display: flex;
      flex-wrap: wrap;
    }

    .equalize {
      flex: 1;
    }
  </style>
</head>
<body>

<div class="equalize-columns">
  <div class="equalize">Content 1</div>
  <div class="equalize">Content 2</div>
  <div class="equalize">Content 3</div>
  <!-- Add more child elements as needed -->
</div>

<script>
  // JavaScript to equalize heights
  window.addEventListener('load', function() {
    equalizeHeights();
  });

  const equalizeHeights = () => {

  const parents = document.querySelectorAll('.equalize-columns');

  parents.forEach(parent => {
    const elements = parent.querySelectorAll('.equalize');
    let maxHeight = 0;

    // Reset heights to 'auto' before recalculating
    elements.forEach(element => {
      element.style.height = 'auto';
      element.style.minHeight = 'auto';
    });

    // Find the maximum height for this parent
    elements.forEach(element => {
      maxHeight = Math.max(maxHeight, element.offsetHeight);
    });

    // Set all elements in this parent to the maximum height
    elements.forEach(element => {
      element.style.minHeight = maxHeight + 'px';
    });
  });
  
  window.addEventListener('resize', function() {
    equalizeHeights();
  });
}
  
}
</script>

</body>
</html>

In this example, the parent element has the class equalize-columns, and child elements have the class equalize. The CSS uses Flexbox to make the children flexible and take up equal space. The JavaScript calculates the maximum height and sets all child elements to that height. The script runs on page load and also when the window is resized to ensure consistent heights.