javascriptjqueryjquery-masonrymasonry

jQuery Masonry items stacking in wrong order


Hard to describe, but this codepen should help make things clear.

With my setup, items are very clearly being stacked in the wrong order.

Most items are 33% width, but I have some 50% width items at the top. I am using a spacer item first, to define the correct size.

For some reason, the 50% items are being stacked on top of each other, when there is very clearly room for them to sit side-by-side. It does this even if I reduce their width to, say 45% - where there is very definitely space for them to sit side-by-side.

It appears to be an actual bug with Masonry, and I have logged an issue with them, but have received no response. Can anyone see why this isn't working? Or provide a fix? Or know of a workaround? Thanks!

For reference, here is the code:

<div class="grid">
  <div class="grid-item grid-item--sizer"></div>
  <div class="grid-item grid-item--width2">1</div>
  <div class="grid-item grid-item--width2">2</div>
  <div class="grid-item grid-item--width2">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
  <div class="grid-item">6</div>
  <div class="grid-item">7</div>
  <div class="grid-item">8</div>
  <div class="grid-item">9</div>
  <div class="grid-item">10</div>
  <div class="grid-item">11</div>
  <div class="grid-item">12</div>
</div>

CSS:

* {
  box-sizing: border-box;
}

.grid {
  background: #EEE;
  max-width: 480px;
  margin:0 auto;
}

.grid-item {
  width: 160px;
  height: 120px;
  float: left;
}

.grid-item--sizer {
  height: 0;
}

.grid-item--width2 {
  width: 240px;
}

JS:

$('.grid').masonry({
  itemSelector: '.grid-item'
});

Solution

  • I think the Masonry layout is based on a columnWidth parameter, and all the grid elements are supposed to have a width that is a multiple of columnWidth. In your case, that would mean having 80px base columns.

    Remove your sizer element (it's not going to be needed), and change your masonry call to:

    $('.grid').masonry({
      itemSelector: '.grid-item',
      columnWidth: 80
    });