Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center OwlCarousel when less than X items

We're using OwlCarousel 1.3.3 on our responsive site. We've set the max number of items to 4.

$container.owlCarousel({
    items: 4,
    itemsDesktop: [1000, 4], 
    itemsDesktopSmall: [900, 3], 
    itemsTablet: [600, 2], 
    itemsMobile: [480, 1]
});

As long as the carousel contains 4 or more images everything works fine. But when an editor only adds 3 or less items we want those items to be centered on the page. Right now they're "left aligned" and it doesn't look very good.

The option itemsScaleUp is not what I'm looking for. If items is set to 4 but the carousel only contains 1 item that item would get too big.

I've found these issues on github:
https://github.com/smashingboxes/OwlCarousel2/issues/35
https://github.com/OwlFonk/OwlCarousel/issues/417
But nothing I find helpful.

You can see the issue in this codepen.

Update:
Looking through the source of OwlCarousel you'll see that the .owl-wrapper elements width gets multiplied with 2. But I can't figure out why, and if it's safe to remove the multiplier.

I've opened this github issue to try to get some clarification.

like image 603
pstenstrm Avatar asked Jun 23 '15 12:06

pstenstrm


2 Answers

In the new version of Owl Carousel 2, you need add this css:

.owl-stage{
    margin: 0 auto;
}

this work's for me in the version 2.

Regards!

like image 108
Radames E. Hernandez Avatar answered Sep 27 '22 23:09

Radames E. Hernandez


Instead of changing source you can use afterInit and ufterUpdate methods. Something like this:

        var owl = $('#carousel');
         owl.owlCarousel({
                        items 6,
                        afterInit: function () {
                            owl.find('.owl-wrapper').each(function () {
                                var w = $(this).width() / 2;
                                $(this).width(w);
                                $(this).css('margin', '0 auto');
                            });
                        },
                        afterUpdate: function () {
                            owl.find('.owl-wrapper').each(function () {
                                var w = $(this).width() / 2;
                                $(this).width(w);
                                $(this).css('margin', '0 auto');
                            });
                        }
                    });
like image 37
Vlad Los Avatar answered Sep 27 '22 22:09

Vlad Los