Responsive Equal Height Columns in Bootstrap

For a recent project, I had some boxes containing content within columns provided by the Bootstrap grid. I wanted the boxes to be the same height, but only on desktops or screens large enough for Bootstrap to show the columns side by side. The boxes did not need to maintain their heights when stacked under each other on mobile screens. Here is the solution I came up with that worked well.

First I put a class of ‘.content-box’ on the boxes containing the content. These boxes were inside the columns provided by Bootstrap. The structure looked like this:

<div class="row">
   <div class="span6">
       <div class="content-box">
       Content here
       </div>
   </div>
   <div class="span6">
       <div class="content-box">
       Content here
       </div>
   </div>
</div>

I then used the following code to make the columns equal height when stacked next to each other, but not when stacked under each other. I called the function when the window was resized so that the boxes are always the correct height when the responsive layouts kick in and I initiated the function using window.load so that all the images have finished loading before the height was decided, otherwise you could end up with columns being to short if the height is applied before an image inside the column finishes loading.


//equal height plugin
$.fn.max = function(selector) {
    return Math.max.apply(null, this.map(function(index, el) {return selector.apply(el);}).get() );
}

$(window).load(function(){
    equalHeight();
});

$(window).resize(function(){
    $('.content-box').css('height', '');
    equalHeight();
});

function equalHeight(){
    if ( $( window ).width() > 768 ) {
        $('.content-box').height(function () {
            var maxHeight = $(this).closest('.row').find('.content-box').max( function () {
                return $(this).height();
            });
            return maxHeight;
            });
    }
    else {
        $('.content-box').css('height', '');
    }
}

2 responses so far

  1. Babu says:

    Awesome.. tutorial!. It was really helpful for me.. Thanks

  2. Nico says:

    Good job!
    It ‘just what I needed for my project.
    Thank you and good programming

What do you think?

Your email address will not be published. Required fields are marked *