Normalize Bootstrap Carousel Item Heights

In working on a Bootstrap-based client project, they needed the heights of all the items to be the same height, even though the content was of different heights.

Bootstrap uses position:absolute to move the items. As such, techniques like flex and grid aren’t of much help here.

The top result on Google as of this writing works but only on one carousel. In an attempt to rewrite the script to work with all carousels on a page, I realized that there was a way to simplify the entire script.

function normalizeSlideHeights() {
      var items = $('.carousel-item', this);
      // reset the height
      items.css('min-height', 0);
      // set the height
      var maxHeight = Math.max.apply(null, 
              return $(this).outerHeight()}).get() );
      items.css('min-height', maxHeight + 'px');

    'load resize orientationchange', 

The original script had a bunch of .each calls that weren’t necessary because jQuery already loops through all items when using methods like .css(). Also, I took advantage of map to avoid an extra loop and used get to convert that into an array that I could run Math.max on.

I’m not sure that orientationchange is necessary since my assumption is that a resize event would also fire but I haven’t tested it and since it was in the original script, I kept it in mine.

Published August 02, 2018
Categorized as JavaScript
Short URL: