Responsive jQuery slideshows with the CSS background-size property

Responsive jQuery slideshows with the CSS background-size property

How to create fully responsive jQuery slideshows using the CSS3 background-size property.

The CSS3 background-size property is the perfect solution to create fully responsive jQuery slideshows that look great even on mobile devices. Basically, this property scales a background image until it fits its container. Let's see a practical example.

The markup used here is very common:

<div id="slideshow">
    <div id="slideshow-wrapper">
        <div class="slide" id="s1"></div>
        <div class="slide" id="s2"></div>
        <div class="slide" id="s3"></div>
        <div class="slide" id="s4"></div>
    </div>
    <div id="slideshow-nav">
        <a href="#s1" class="active">1</a>
        <a href="#s2">2</a>
        <a href="#s3">3</a>
        <a href="#s4">4</a>
    </div>
</div>
​

The CSS uses background images with the background-size property set to contain:

#slideshow {
    margin: 2em auto;
    width: 70%;
    max-width: 40em;
    overflow: hidden;
}

#slideshow-wrapper {
    width: 1600em;
    height: 15em;
    position: relative;
}

div.slide {
    width: 40em;
    height: 15em;
    float: left;
    background-repeat: no-repeat;
    background-size: contain;
}

#s1 {
    background-image: url(slide-1.jpeg);
}

#s2 {
    background-image: url(slide-2.jpeg);
}

#s3 {
    background-image: url(slide-3.jpeg);
}

#s4 {
    background-image: url(slide-4.jpeg);
}

#slideshow-nav {
    margin: 1em 0;
    text-align: center;
}

#slideshow-nav a {
    display: inline-block;
    width: 1.5em;
    height: 1.5em;
    line-height: 1.5;
    border: 1px solid silver;
    color: #333;
    text-decoration: none;
    margin-right: 0.5em;
}

#slideshow-nav a.active {
    background: #000;
    color: #fff;
    border-color: #000;
}​

Finally, the jQuery code used here is purely demonstrative:

var Slideshow = {
    
    navigate: function() {
        $('a', '#slideshow-nav').click(function(e) {
            e.preventDefault();
            var $a = $(this);
            var slide = $($a.attr('href'));
            var wrapper = $('#slideshow-wrapper');

            wrapper.animate({
                left: -slide.position().left
            }, 1000, 'linear', function() {
                $a.addClass('active').siblings().removeClass('active');
            });

        });
    },

    init: function() {
        this.navigate();
    }

};


Slideshow.init();
​

You can see the demo below.

Demo

Live demo