简体   繁体   中英

Match element's height

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?

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/

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 )

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)

JSFiddle Example

var maxHeight = 0;
$(".services-area").each(function () {
    maxHeight = Math.max(maxHeight, $(this).height());
}).height(maxHeight);  

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM