Home  >  Article  >  Web Front-end  >  How to Make All Elements in a Group the Same Height with jQuery or CSS?

How to Make All Elements in a Group the Same Height with jQuery or CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 13:06:02611browse

How to Make All Elements in a Group the Same Height with jQuery or CSS?

Finding the Tallest of All Elements Using jQuery or CSS

Question:

How can we use jQuery or CSS to determine the tallest of a group of elements (DIVs) and set all of them to the same height?

Solution Using jQuery:

  1. Utilize a loop to iterate through each element and identify the tallest one by comparing their heights.
  2. Set the heights of the remaining elements to match the height of the tallest element.
$(document).ready(function() {
   var maxHeight = -1;

   $('.features').each(function() {
     maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
   });

   $('.features').each(function() {
     $(this).height(maxHeight);
   });
});

Version 2 (Cleaner Using Functional Programming):

$(document).ready(function() {
  var maxHeight = Math.max.apply(null, $('.features').map(function() {
    return $(this).height();
  }).get());

  $('.features').height(maxHeight);
});

Solution Using Vanilla JavaScript (without jQuery):

var elements = document.getElementsByClassName('features');

var maxHeight = Math.max.apply(null, Array.prototype.map.call(elements, function(el)  {
  return el.clientHeight;
}));

Array.prototype.forEach.call(elements, function(el) {
  el.style.height = maxHeight + "px";
});

Using ES6:

const elements = document.getElementsByClassName('features');

const maxHeight = Math.max(...Array.from(elements).map(el => el.clientHeight));

elements.forEach(el => el.style.height = `${maxHeight}px`);

Conclusion:

These methods effectively ensure that a set of DIVs have equal heights, regardless of their content, using jQuery, vanilla JavaScript, or ES6.

The above is the detailed content of How to Make All Elements in a Group the Same Height with jQuery or CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn