--- layout: default title: Using images with Shuffle description: A Shuffle.js demo using aspect ratios to set the size of images. image: /demos/images.jpg extraJS: ["demos/images.js"] prism: true ---

Using images with Shuffle

You can encounter problems when shuffle item dimensions depend on images. Like this demo. There are three good solutions to this.

  1. Set an explicit height on .shuffle-items like the basic demo.
  2. Similar to number 1, make the height of the image container a percentage of the width. If you know the aspect ratio of the images you're using, this is the technique you should use. This demo uses that technique.
  3. Get notified when images load and call shuffleInstance.layout(). I recommend using Desandro's images loaded plugin to know when your images have finished loading.
  4. Do nothing and let your shuffle instance call layout() on the window's load event. This will the item layout to change on page load.
{% for item in site.data.items %}
{{ item.description }}
{{ item.title }}
{% endfor %}

Setup

Maintaining aspect ratios

With two elements, you can create a box which will scale with the page. Here's an example:

A 2:1 box

With this knowledge, you can force an image to fit inside this box and, when the image loads, it will not change the size of the box.

.aspect {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 100%;
  overflow: hidden;
}

.aspect__inner {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

/* Add more aspect ratios here */
.aspect--16x9 {
  padding-bottom: 56.25%;
}

Markup for each item

The most important thing here is that the images are wrapped in two other elements which define its size. This means that the size of the <figure> does not depend on the image.

<figure class="js-item img-item col-3@sm col-3@xs">
  <div class="aspect aspect--16x9">
    <div class="aspect__inner">
      <img src="/img/tennis-ball.png" alt="3D render of a tennis ball">
    </div>
  </div>
  <figcaption>wallpaper, 3d</figcaption>
</figure>

JavaScript used for this demo

Link to demo source