Image slider: maintaining equal height for all images while keeping slider responsive

drake035 picture drake035 · Feb 5, 2014 · Viewed 75.9k times · Source

In my JS image slider (Owl-Carousel), images have different dimensions:

http://goo.gl/KmpX2P

enter image description here

You can see that the image height varies within the carousel. How to make it constant while keeping carousel responsive? I need images to fill the slider space at all times, therefore some will have to be cropped through CSS somehow. The desired result looks like this:

enter image description here

Answer

melc picture melc · Feb 7, 2014

It can be specified in css.

Example,

http://jsfiddle.net/AwBLL/2/

.owl-carousel .owl-item{
    height:285px;
    width:100%;
}

EDIT The following solution uses the plugin's callback events to modify the viewport's/wrapper's height according to the smallest image height.

http://jsfiddle.net/DNMpF/1/

js

$(document).ready(function () {

    $("#owl-example").owlCarousel({
        afterUpdate: function () {
            updateSize();
        },
        afterInit:function(){
            updateSize();
        }
    });
    function updateSize(){
        var minHeight=parseInt($('.owl-item').eq(0).css('height'));
        $('.owl-item').each(function () {
            var thisHeight = parseInt($(this).css('height'));
            minHeight=(minHeight<=thisHeight?minHeight:thisHeight);
        });
        $('.owl-wrapper-outer').css('height',minHeight+'px');
    }
});

css

.owl-carousel .owl-item img {
    height:auto;
    width:100%;
    display: block;
}

.owl-carousel .item {
    margin:0px;
}

EDIT2

Regarding the latest comment, to show the bottom part of the large images one approach could be to iterate the images and add a negative top margin equal to the part of these images hidden.

function updateSize(){
        var minHeight=parseInt($('.owl-item').eq(0).css('height'));
        $('.owl-item').each(function () {
            var thisHeight = parseInt($(this).css('height'));
            minHeight=(minHeight<=thisHeight?minHeight:thisHeight);
        });
        $('.owl-wrapper-outer').css('height',minHeight+'px');

        /*show the bottom part of the cropped images*/
        $('.owl-carousel .owl-item img').each(function(){
            var thisHeight = parseInt($(this).css('height'));
            if(thisHeight>minHeight){
                $(this).css('margin-top',-1*(thisHeight-minHeight)+'px');
            }
        });

    }