Search code examples
jqueryhtmlcssbxslider

Horizontally centering the active image of a bxSlider carousel with a seamless loop?


I want to make a really simple seamlessly-looping carousel and have tried using bxSlider, but am encountering an issue where my images are off-center.

I have 3 x 1000px wide images and all I want to do is ensure the active image is in the middle of the browser, with the other two images infinitely looping on the left/right sides, like so:

enter image description here

I've tried using a negative-margins trick (left: 50% and margin-left: -500px) but it didn't work and bxSlider went kind of crazy.

My code is very simple and I have a fiddle here: http://jsfiddle.net/j3hgA/

<ul class="bxslider">
    <li><img src="http://i.imgur.com/pOh3bXm.jpg" /></li>
    <li><img src="http://i.imgur.com/VrvQUzu.jpg" /></li>
    <li><img src="http://i.imgur.com/pJr77Ee.jpg" /></li>
</ul>

Is there a better way to do this?


Solution

  • This was a "simple" CSS problem.

    I'd set my carousel's .bx-wrapper to 5000px wide, to accommodate the main 3 × 1000px wide slides, plus the 2 × 1000px wide "overflow" slides which bxSlider generates to the left and right of the carousel to achieve the "seamless" effect.

    I therefore should have had margin-left: -2500px; left: 50%; on my carousel's main wrapper div. That is, a margin-left that is half of the total width of the whole carousel, not just of one image.

    The final CSS, therefore, was something like:

    #slideshow-wrapper {
        width: 1000px;        /* Width of single slide */
        margin-left: -2500px; /* Half of total carousel width including overflow images */
        left: 50%;
    }
    
    #slideshow-wrapper .bx-wrapper {
        width: 5000px !important; /* Total width including overflow images */
        margin: 0 auto;
        position: relative;
    }
    

    Finally, I was seeing a "white flash" or "pop-in" to the right of the slider every time it looped. This was because I hadn't set bxSlider's displaySlideQty option, which determines how many slides should be visible on the screen at any time.

    The default displaySlideQty is 1, but in my case, I actually had parts of 3 images displayed in the viewport, so bxSlider wasn't pre-rendering the left/right "overflow" or "seamless" images at the right time. Changing displaySlideQty to 3 worked, and the slideshow loops infinitely.

    $("#slider").bxSlider({
        moveSlides: 1,
        displaySlideQty: 2,
        responsive: false,
        infiniteLoop: true
    });