How do I keep two side-by-side divs the same height?

后端 未结 22 2763
自闭症患者
自闭症患者 2020-11-21 07:56

I have two divs side by side. I\'d like the height of them to be the same, and stay the same if one of them resizes. I can\'t figure this one out though. Ideas?

To c

22条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 08:19

    This is a jQuery plugin which sets the equal height for all elements on the same row(by checking the element's offset.top). So if your jQuery array contains elements from more than one row(different offset.top), each row will have a separated height, based on element with maximum height on that row.

    jQuery.fn.setEqualHeight = function(){
    
    var $elements = [], max_height = [];
    
    jQuery(this).css( 'min-height', 0 );
    
    // GROUP ELEMENTS WHICH ARE ON THE SAME ROW
    this.each(function(index, el){ 
    
        var offset_top = jQuery(el).offset().top;
        var el_height = jQuery(el).css('height');
    
        if( typeof $elements[offset_top] == "undefined" ){
            $elements[offset_top] = jQuery();
            max_height[offset_top] = 0;
        }
    
        $elements[offset_top] = $elements[offset_top].add( jQuery(el) );
    
        if( parseInt(el_height) > parseInt(max_height[offset_top]) )
            max_height[offset_top] = el_height;
    
    });
    
    // CHANGE ELEMENTS HEIGHT
    for( var offset_top in $elements ){
    
        if( jQuery($elements[offset_top]).length > 1 )
            jQuery($elements[offset_top]).css( 'min-height', max_height[offset_top] );
    
    }
    

    };

提交回复
热议问题