jQuery Cycle2 slideshow with responsive height, as well as width

Sam Baldwin picture Sam Baldwin · Apr 2, 2013 · Viewed 14.2k times · Source

I'm trying to create a slideshow of images using the jQuery Cycle2 plugin that will be responsive, adjusting to the browser width and height. I was able to use the Dynamic Container Sizing docs from the Auto Height feature to get the width working well.

See the fiddle I made here, which is a simplified representation of a website build I'm working on.

Is it possible to somehow give the slides a max-height:100%; of the .cycle-slideshow div?

Broadly speaking, the problem I am facing is that long portrait images do not really fit into the design of my site and the user has to scroll to see the full image, which isn't fantastic.

Many thanks.

Answer

Charles Butler picture Charles Butler · Aug 21, 2013

A little late on this one but I will give it a shot.

Assuming all your images are NOT the same height: This is a little trick to always keep your container the same size even with different dimension images.

Pseudo terms:

  1. Make your images the 'background' of the slide instead of positioned within.
  2. Add a {background-size: cover} to the CSS.
  3. Use Cycle2's custom template to initiate this. (hack? ehh, not really)

Let's get some new CSS rules:

.cycle-overlay {
    position:absolute;
    bottom:auto;
    top:0;
    left:0;
    width:100%;
    height:100%;
    z-index:0;
    background:#333;
    padding:0;
    opacity:1
}
.banner-background {
    width:100%;
    height:100%;
    background-position:center;
    background-size:cover;
    position:absolute;
    top:0;
    left:0;
    z-index:10;
}
.cycle-slideshow {
    width:100%;
    max-height:400px;
    background-position:center;
    background-size:cover;
    color:#fff;
    overflow:hidden;
}

The HTML

<div class="cycle-slideshow" 
  data-cycle-slides='li' 
  data-cycle-fx='scrollHorz' 
  data-cycle-speed='700' 
  data-cycle-timeout='7000'    
  data-cycle-overlay-template="<div class=banner-background style=background-image:url(http://domain.tld/images/{{background}})></div>" 
>
    <ul>
       <li data-cycle-background="slide1.jpg"></li>
       <li data-cycle-background="slide2.jpg"></li>
       <li data-cycle-background="slide3.jpg"></li>
    </ul>
    <div class="cycle-overlay"></div>
        </div>

The JS

$('.cycle-slideshow').on('cycle-before', function (opts) {
    var slideshow = $(this);
    var img = slideshow.find('.banner-background').css('background-image');
    slideshow.css('background-image', img);
});

Assuming all your images are the same height: I wrote an example a few months back about integrating animate.css with Cycle2

It isn't what you are looking for but the example provides a full-width auto-height solution.

Check out the code and you will get what you need.

Fiddle here!

Also, remember with Cycle2 you need to add the extra plugin to center slides jquery.cycle2.center.js

Hope this helps, cheers!