Reputation: 16748
I've got a few <div>
elements next to each other and I'd like to match their height to the highest one. Currently I do it like this:
jQuery(function($) {
var maxHeight = 0;
$( ".services-area").each (function (index ) {
if (maxHeight < $( this ).height()) {
maxHeight = $( this ).height();
}
});
$( ".services-area").each (function (index ) {
$( this ).height(maxHeight);
});
})
Are there better ways to achieve this result?
Upvotes: 2
Views: 266
Reputation: 905
Personally, I do this:
$.fn.sameHeight = function(){
var max = 0;
this.each(function(){
max = Math.max($(this).height(),max);
});
return this.height(max);
};
Then I can just call it when ever I want
$('.column').sameHeight();
See Live example here http://jsfiddle.net/Panomosh/t6xsjef7/
Upvotes: 4
Reputation: 7117
var maxHeight = 0;
$(".services-area").each(function () {
maxHeight = Math.max(maxHeight, $(this).height());
}).height(maxHeight);
Upvotes: 0
Reputation: 16979
Here is another way you can approach this, leveraging the JavaScript max()
Method
var max = Math.max.apply(Math, $('.services-area').map(function() {
return $(this).height();
}));
$('.services-area').height(max)
Upvotes: 1
Reputation: 8663
You could use CSS flex box:
.container {
display: flex;
align-items: stretch; // Matches height of items
justify-content: space-between; // Arranges horizontally
}
Quick pen: http://codepen.io/alexcoady/pen/KpgqGB
Works in all modern browsers, with partial support for IE10, but fails before that (http://caniuse.com/#search=flex)
Upvotes: 2