Make Selected Elements Have A Uniform Height

Make Selected Elements Have A Uniform Height
File Size: 3.15 KB
Views Total: 53
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

There are many ways today to solve for equal height elements on modern web development. The best two ways are to use CSS flexbox and Grid Layout.

But if you're looking for a cross-browser solution to make certain elements (such as divs) have a uniform height, this article is right for you.

This is a simple and lightweight jQuery function that can be used to make the selected elements have the same height. It works by calculating the difference in heights of the elements and then setting the height of all other elements to match this difference, thus ensuring that all elements have the same height.

How to use it:

1. The main function to loop through all elements in a group and set the height of all those children to whichever was highest. Copy the snippets below and insert them after you load the latest jQuery library.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
function mam_set_auto_height() {
  // reset sh-active class
  $('.sh-active').css('height', 'auto');
  $('.sh-active').removeClass('sh-active');

  // get all elemets with same height data
  $ashElements = $("[data-same-height]");
  // loop through the elements
  $ashElements.each(function () {
      $element = $(this);

      // skip if it's been configured already or not
      if ($element.hasClass('sh-active')) {
          return true;
      }
      // get group to set same height
      var _group = $element.attr('data-same-height');

      // get group elements
      $groupElements = $('[data-same-height="' + _group + '"]');

      // Cache the highest
      var highestBox = 0;

      // loop throgh the group elements
      $groupElements.each(function () {
          // If this box is higher than the cached highest then store it
          if ($(this).height() > highestBox) {
              highestBox = $(this).height();
          }
      });
      // Set the height of all those children to whichever was highest
      $groupElements.addClass('sh-active').height(highestBox);
  });
}

2. Add the data-same-height attribute to the elements which will have the same height.

<div data-same-height="group-1">
  ...
</div>

<div data-same-height="group-1">
  ...
</div>

<div data-same-height="group-1">
  ...
</div>

...

3. Call the mam_set_auto_height() function on document ready.

mam_set_auto_height();

4. Re-init the mam_set_auto_height() on page load & resize.

$(window).on('load',function () {
  mam_set_auto_height();
});

$(window).on('resize',function () {
  mam_set_auto_height();
});

This awesome jQuery plugin is developed by moveaheadmedia. For more Advanced Usages, please check the demo page or visit the official website.