Home > Article > Web Front-end > How to Make All Elements in a Group the Same Height with 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:
$(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!