Question

Per the example in the Masonry documentation, http://masonry.desandro.com/options.html, I centre my Masonry layout by setting isFitWidth = true, and setting {margin: 0 auto} on the Masonry container.

When I have loads of items to display this is a really nice solution. For example, let's say my viewport is just over 5 columns wide, I will see all the items laid out, 5 to a row, and the whole container centred within my viewport. Lovely.

The problem arises when I have less than 5 items. In this case, the container remains centred in the viewport, but it shrinks to fit the number of items. So if I have, for example, two items, I will have two columns in the middle of the screen, with one item each.

What I would like to see is the container maintain is size (in this example, 5 columns), and remain centred, and lay the content out LTR (in my case).

I have experimented with media queries and setting a minimum width for the container based on the viewport. This looks like it will work, but it's messy - I don't fancy having to update the media queries (including recalculating all the gross container widths) each time my column size changes. (I'm sure users will want some changes).

Another solution might be to add some fake items to the content and set their visibility to hidden, but this is not exactly elegant either.

Is there a more simple solution that I'm missing?

One additional point - I am stamping some items in place too, top left and top right. I don't think this should affect any solutions.

Was it helpful?

Solution

OK, So the only way I could find to do this effectively was to use media queries. I setup a spreadsheet to help recalculate things when I changed column and gutter sizes. Here's the variables and equations, in case they are helpful:

If:

  • WC = Width of column
  • WG = Width of gutter
  • N = Number of columns
  • CON = Width of container

Then:

  • CON = N*WC + (N-1)*WG

You can set up a spreadsheet and experiment with WC and WG, and a range of N=1...10 This will give you the size of CON for each value of N. The width of the viewport needs to be CON plus any horizontal margin and padding on CON (or its parent).

To set media queries I took the approach that the container should be as wide as possible, but still neatly accommodate exact columns. So, for example, if the viewport can accommodate 5 columns, (but not quite 6), I set the corresponding min-width on CON. This leave the container neatly centred.

By way of example, here is one of my media queries:

@media (min-width: 996px) and (max-width: 1361px) { .content-container { min-width: 966px; } }

I hope this is helpful to someone. I'll leave the question open for a few days in case there are other solutions forthcoming.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top