user1910388
user1910388

Reputation: 235

Responsive grid with masonry

I want to build a responsive masonry grid like THIS

I have this HTML

<div class="js-masonry" data-masonry-options='{ "gutter": 20 }'>
  <article></article>
  <article></article>
  <article></article>
  <article></article>
  <article></article>
  <article></article>
</div>

and the SCSS

article{
width: 100%;
float: left;

    @include breakpoint(medium) {
        width: 50%;
    }

    @include breakpoint(large) {
        width: 33.33333%;
    }
}

When I remove the gutter daclared in the html the grid works as I want, but with it it displays 2 at the large breakpoint and 1 at medium. How can I get this to work with using margins to space out the article horizontally?

Upvotes: 0

Views: 1169

Answers (1)

Anders Flink
Anders Flink

Reputation: 81

The problem is that masonry.js adds a margin to the element making the element 50% + 20px wide, with is to big to fit on one row.

The solution is to make the elements and gutter fit in your wrapper by making the gutter + elements in a row = wrapper. If you have a flexible layout this would be a problem as masonry.js only takes a fixed px as gutter size.

So if (like in you example) you make the elements a fixed width this would be no problem. But masonry.js has a solution; if you sett the gutter not to a fixed width but to a element, masonry.js will use the width of that element. So a flexible solution could be to do this:

<div class="js-masonry" 
  data-masonry-options='{ "gutter": ".gutter-sizer", "itemSelector": "article"}'>

  <div class="gutter-sizer"></div>
  <article></article>
  <article></article>
  <article></article>
  <article></article>
  <article></article>
  <article></article>
</div>

and the Scss

article {
  width: 100%;
  float: left;
  @include breakpoint(medium) {
    width: 49.2%;
  }
  @include breakpoint(large) {
    width: 32.26%;
  }
}
.gutter-sizer {
  width: 0%;
  @include breakpoint(medium and large) {
    width: 1.6%; //About 20px on a regular monitor at full width.
  }
}

Upvotes: 2

Related Questions