pstenstrm pstenstrm - 5 months ago 157
CSS Question

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.

Answer

OwlCarousel has a 2x multiplier on the .owl-wrapper elements width. This multiplier makes it incredibly hard to center the carousel when it's less than full.

However, this multiplier doesn't seem to have any reason to be there. Nothing seems to break when I remove it. So that's what I did, the updated owl.carousel.js can be found here: https://github.com/Vinnovera/OwlCarousel/tree/remove-width-multiplier

And I added this CSS (which is not included in the repo):

.owl-wrapper {
    margin: 0 auto;
}