Automatic Image Montage with jQuery

Arranging images in a montage like fashion can be a challenging task when considering certain constraints, like the window size when using fullscreen, the right image number to fill all the available space or also the size of the images in use. With the following script you can automatically create a montage, either for a liquid container or a fixed size container (including fullscreen), with the option to fill all the gaps.
Automatic Image Montage with jQuery

From our monthly sponsor: Automate manual QA and catch visual bugs with Percy’s all-in-one visual testing and review platform.

Arranging images in a montage like fashion can be a challenging task when considering certain constraints, like the window size when using fullscreen, the right image number to fill all the available space or also the size of the images in use. With the following script you can automatically create a montage, either for a liquid container or a fixed size container (including fullscreen), with the option to fill all the gaps.

Having a white space in the end of the container can, as well, be avoided optionally. The last image of the montage can fill the left space, so that the montage will be left gap-less.

Another option that can be useful in some cases is the possibility to only allow that the height of all images will be the height of the smallest image, avoiding that any picture gets pixelated/enlarged. (The default options will allow the enlargement of smaller images if there is a significantly higher number of larger images in the set.)

The images used in the demos are by Andrey Yakovlev & Lili Aleeva. They are licensed under the Attribution-NonCommercial 3.0 Unported License.

The HTML structure

Simply put the images that you want to use in the montage into a container with the following class (the ID is used to call the plugin then):

<div class="am-container" id="am-container">
	<a href="#"><img src="images/1.jpg" title="Image 1"></img></a>
	<a href="#"><img src="images/2.jpg" title="Image 2"></img></a>
	<a href="#"><img src="images/3.jpg" title="Image 3"></img></a>
	...
</div>

The default style that we give to this container and the images is the following:

.am-wrapper{
	float:left;
	position:relative;
	overflow:hidden;
}
.am-wrapper img{
	position:absolute;
	outline:none;
}

Since we don’t define any width for the container, the above example will show the montage in fullscreen.

If you would like to use a container with a fixed width, you can simply add a width.

In case you’d like to have a container with a fixed height and width and with a vertical scrollbar, then you need to add another wrapper around the container:

<div style="width:800px;height:300px;overflow-y:scroll; margin:40px auto;">
	<div class="am-container" id="am-container">
	...
	</div>
</div>

Options

There are several options for this plugin. The default ones are the following:

// If you use percentages (or no width at all)
// for the container's width, then set this to true.
// This will set the body's overflow-y to
// 'scroll' (fix for the scrollbar's width problem)
liquid					: true, 

// Space between images in pixels
margin					: 1,	

// The minimum width that a picture should have
minw					: 70,	

// The minimum height that a picture should have
minh					: 20,	

// The maximum height that a picture should have
maxh					: 250,	

// Alternate the height value for every row.
// If true this has priority over defaults.fixedHeight
alternateHeight			: false,
// The height will be a random value between 'min' and 'max':
alternateHeightRange	: {
	min	: 100,
	max	: 300
},

// If the following value is set, this will
// have priority over defaults.minsize.
// All images will have this height:
fixedHeight				: null,	

// Setting this value will make minw, minh irrelevant.
// Chosen height will be the one of the smallest image
// when this is set to true:
minsize					: false,

// If true, there will be no gap in the end
// of the container. The last image will
// fill any white space left:
fillLastRow				: false

There are quite some possibilities with these options and some of them can be seen in the demos (you can jump to the other demos in each example):

  • Example 1: Fullscreen liquid example with alternating heights, last image will fill the last row. Refresh the browser to see a different arrangement
  • Example 2: Fullscreen liquid example with alternating heights and no margin, last image will fill the last row
  • Example 3: Fullscreen liquid example with alternating heights and bigger margin, last image will fill the last row
  • Example 4: Fixed width container example with fixed height for images. Click “load more” (end of page) in order to see how more images can be added
  • Example 5: Fixed width and height of a wrapper with scrollbar, last image will fill the last row
  • Example 6: Minimum width of images with alternating heights of rows and large margin, last image will fill the last row. Click “load more” (end of page) in order to see how more images can be added
  • Example 7: Liquid container example with fixed height for images. Resize the browser to see the change
  • Example 8: Guarantees that no image will be pixelated by choosing the minimum height available (last image cannot fill the last row). Click “load more” (end of page) in order to see how more images can be added

In each example you can view which options were used to achieve the layout/functionality.

Hope you find it useful, feedback is welcome!

Tagged with:

Receive our bi-weekly Collective or official newsletter right in your inbox.

CSS Reference

Learn about all important CSS properties from the basics with our extensive and easy-to-read CSS Reference.

It doesn't matter if you are a beginner or intermediate, start learning CSS now.

Feedback 72

Comments are closed.
  1. Thank you for nice demo! I like it a lot and working on it to adapt to my photographic portfolio!

    One thing I would like to see is to display images in batches, if you have 50+ images loading part is quite long!!!

  2. Thanks Pedro, great script!

    Hope You can help me with Montage and «infinite scroll».

    I have some problem: when new img loading by scrolling, montage is’t working with them.

    Sorry, bad english.

  3. Really, it’d be great if someone could share how they got this to work with a simple Lightbox style script so that when you click an image it enlarges it and fades out the background.

  4. Well, the answer to my question on my own.

    If You want to use Montage and Infinite-Scroll use about such a structure:

    $(function(){

    var $container = $(‘#am-container’),
    $img = $container.find(‘img’).css({ opacity: 0 });

    $container.imagesLoaded(function(){
    $img.animate({ opacity: 1 });
    $container.montage({
    minw : 200,
    alternateHeight : true,
    alternateHeightRange : {
    min : 100,
    max : 250
    },
    margin : 8,
    fillLastRow : true
    });
    }).attr(‘src’,$img.attr(‘src’));
    $img.show();

    $container.infinitescroll({
    navSelector : ‘.nav-previous’, // selector for the paged navigation
    nextSelector : ‘.nav-previous a’, // selector for the NEXT link (to page 2)
    itemSelector : ‘.post’, // selector for all items you’ll retrieve
    loading: {
    finishedMsg: ‘No more pages to load.’,
    img: ‘./i/loading.gif’
    }
    },
    function( newElements ) {
    var $newElems = $( newElements ).css({ opacity: 0 });
    $newElems.imagesLoaded(function(){
    $newElems.animate({ opacity: 1 });
    $container.append( $newElems ).montage( ‘add’, $newElems, {
    minw : 200,
    alternateHeight : true,
    alternateHeightRange : {
    min : 100,
    max : 250
    },
    margin : 8,
    fillLastRow : true
    } );

    });
    }
    );

    });

  5. I try 1st example of the demo with images 175px x 100px, and modify my index.html with alternateHeight to false.

    But the problem is that the last image of each rows don’t manage to reach the right of the screen.

    The image that had to be the last image of the row appears as the 1st image of the next row and redimensioned with the same width that the blank space that appears on the previous row.

    Thank you for your help .

  6. Hi there, has anyone tried to use this in conjunction with any form of Lightbox functionality to enlarge the images??

    Cheers,
    Tyler

  7. Hi there, also has anyone noticed that on some rows of images, the overall row width doesn’t match the majority of the others.. i.e. the nice harsh line down the side of the page is a little bit broken due to some rows?

    Cheers
    Tyler

  8. Is it possible to “change” the script so it doesn’t crop the pictures when they are forced smaller, but just “resizes”?

  9. Hello! Thanks for this great script! I have some troubles with links. How can I make around every ? Every img should have unique link. When I write script doesn’t work((

  10. hey man~ this script just can only be run in a separate DIV
    I hope to achieve the same functionality in multiple DIV, what to do?

  11. Hi. Great script. I’m doing a gallery divided into sections, every section a “montage” div. However, only the first div is “transformed” into a montage. Is there a way to get all montage divs to transform? It works if I wrap all the sections in the montage div, but then it clumps all the images together and I want every section to be separate.

    Thanks.

    • Solved if myself:

      $(window).load(function () {

      $(‘.container’).each(function(){
      var $container = $(this),
      $imgs = $container.find(‘img’).hide(),
      totalImgs = $imgs.length,
      cnt = 0;

      $imgs.each(function (i) {
      var $img = $(this);
      $(”).load(
      function () {
      ++cnt;
      if (cnt === totalImgs) {
      $imgs.show();
      $container.montage({
      minw:120,
      liquid:false,
      alternateHeight:true,
      alternateHeightRange:{
      min:120,
      max:480
      },
      margin: ,
      fillLastRow:true
      });

      }
      }).attr(‘src’, $img.attr(‘src’));
      });
      });
      });

  12. I used this script to built an extension for joomla 1.7 – 2.5 with lightbox function. Thanks to all guys from codrops for so many inspiration.

  13. var $container = $(‘#am-container’),
    $imgs = $container.find(‘img’).hide(),
    totalImgs = $imgs.length,
    cnt = 0;

    I deleted the .hide(), so that the images dont have wait till all the images are loaded to be display,though it sacrifice some beauty of the image grid before all images are displayed
    anyone have any better solution to speed up the image display time?