By Pekka supports GoFundMonica


2017-06-05 20:41:22 8 Comments

I need to implement a fairly run-off-the-mill masonry layout. However, for a number of reasons I don't want to use JavaScript to do it.

A grid of multiple columns of rectangles of varying height.

Parameters:

  • All elements have the same width
  • Elements have a height that cannot be calculated server side (an image plus various amounts of text)
  • I can live with a fixed number of columns if I have to

there is a trivial solution to this that works in modern browsers, the column-count property.

The problem with that solution is that elements are ordered in columns:

Starting from the top leftmost box, they're numbered 1 through 4 straight down, the topmost box in the next column is 5, and so on.

While I need the elements to be ordered in rows, at least approximately:

Starting from the top leftmost box, they're numbered 1 through 6 straight across, but because box 5 is the shortest the box underneath it is 7 as it has the appearance of being on a row higher than the next box on the far left.

Approaches I've tried that don't work:

Now I could change the server side rendering and reorder the items dividing the number of items by the number of columns, but that's complicated, error-prone (based on how browsers decide to split the item list into columns), so I'd like to avoid it if possible.

Is there some newfangled flexbox magic that makes this possible?

2 comments

@Oliver Joseph Ash 2019-06-15 16:33:43

This is recently discovered technique involving flexbox: https://tobiasahlin.com/blog/masonry-with-css/.

The article makes sense to me, but I haven't tried to use it, so I don't know if there are any caveats, other than mentioned in Michael's answer.

Here's a sample from the article, making use of the order property, combined with :nth-child.

Stack snippet

.container {
  display: flex;
  flex-flow: column wrap;
  align-content: space-between;
  /* Your container needs a fixed height, and it 
   * needs to be taller than your tallest column. */
  height: 960px;
  
  /* Optional */
  background-color: #f7f7f7;
  border-radius: 3px;
  padding: 20px;
  width: 60%;
  margin: 40px auto;
  counter-reset: items;
}

.item {
  width: 24%;
  /* Optional */
  position: relative;
  margin-bottom: 2%;
  border-radius: 3px;
  background-color: #a1cbfa;
  border: 1px solid #4290e2;
  box-shadow: 0 2px 2px rgba(0,90,250,0.05),
    0 4px 4px rgba(0,90,250,0.05),
    0 8px 8px rgba(0,90,250,0.05),
    0 16px 16px rgba(0,90,250,0.05);
  color: #fff;
  padding: 15px;
  box-sizing: border-box;
}

 /* Just to print out numbers */
div.item::before {
  counter-increment: items;
  content: counter(items);
}

/* Re-order items into 3 rows */
.item:nth-of-type(4n+1) { order: 1; }
.item:nth-of-type(4n+2) { order: 2; }
.item:nth-of-type(4n+3) { order: 3; }
.item:nth-of-type(4n)   { order: 4; }

/* Force new columns */
.break {
  flex-basis: 100%;
  width: 0;
  border: 1px solid #ddd;
  margin: 0;
  content: "";
  padding: 0;
}

body { font-family: sans-serif; }
h3 { text-align: center; }
<div class="container">
  <div class="item" style="height: 140px"></div>
  <div class="item" style="height: 190px"></div>
  <div class="item" style="height: 170px"></div>
  <div class="item" style="height: 120px"></div>
  <div class="item" style="height: 160px"></div>
  <div class="item" style="height: 180px"></div>
  <div class="item" style="height: 140px"></div>
  <div class="item" style="height: 150px"></div>
  <div class="item" style="height: 170px"></div>
  <div class="item" style="height: 170px"></div>
  <div class="item" style="height: 140px"></div>
  <div class="item" style="height: 190px"></div>
  <div class="item" style="height: 170px"></div>
  <div class="item" style="height: 120px"></div>
  <div class="item" style="height: 160px"></div>
  <div class="item" style="height: 180px"></div>
  <div class="item" style="height: 140px"></div>
  <div class="item" style="height: 150px"></div>
  <div class="item" style="height: 170px"></div>
  <div class="item" style="height: 170px"></div>
  
  <span class="item break"></span>
  <span class="item break"></span>
  <span class="item break"></span>
</div>

@LGSon 2019-06-15 17:45:07

First off, link only answers is bad ones, as when such link dies, so does the answer. Second, if you read the given answer more carefully, you'll find what's mentioned in your link is covered. Simply put, there are too many limitations using Flexbox alone, unless what is mentioned above is not an issue.

@Oliver Joseph Ash 2019-06-15 18:22:59

I have read the accepted answer very thoroughly—you'll even see some comments I added to the bottom of it. The flexbox approach I linked to is unique and not covered by that answer. I don't want to repeat the article, because it's very complicated, and the article does a great job of covering that.

@LGSon 2019-06-15 18:39:15

The only thing that the linked does different is making use of the order property, making it look like items flows from left to right. Still, its main trick is flex-flow: column wrap, which is mentioned in the above answer. In addition, it can't flow the items in the way a real masonry does, e.g. if the 3rd and 4th item would fit in the 3rd column, they would, the linked one doesn't. But again as I said, it all depends on what the requirements are, and in this case (this question), it won't work as what asked for.

@LGSon 2019-06-15 18:41:27

Furthermore, it is not about "you don't want to repeat the article", an answer should contain the essential part of the code, so it will still be valid when the linked resource dies.

@Oliver Joseph Ash 2019-06-15 18:48:04

Fair points. I thought it would be useful to share this article here anyway, since it builds upon the other techniques mentioned previously, and whilst it doesn't answer the original question, it might help others for whom these limitations are acceptable. I'm happy to delete my answer and re-share the link as a comment, noting the key difference (order).

@LGSon 2019-06-15 18:50:27

It is useful, though as a link alone, do it as a comment, if you edit in the code, keep it as an answer.

@LGSon 2019-06-15 18:55:40

I updated it, added a sample from article + an upvote.

@Michael_B 2017-07-19 21:03:27

Flexbox

A dynamic masonry layout is not possible with flexbox, at least not in a clean and efficient way.

Flexbox is a one-dimensional layout system. This means it can align items along horizontal OR vertical lines. A flex item is confined to its row or column.

A true grid system is two-dimensional, meaning it can align items along horizontal AND vertical lines. Content items can span across rows and columns simultaneously, which flex items cannot do.

This is why flexbox has a limited capacity for building grids. It's also a reason why the W3C has developed another CSS3 technology, Grid Layout.


row wrap

In a flex container with flex-flow: row wrap, flex items must wrap to new rows.

This means that a flex item cannot wrap under another item in the same row.

Notice above how div #3 wraps below div #1, creating a new row. It cannot wrap beneath div #2.

As a result, when items aren't the tallest in the row, white space remains, creating unsightly gaps.


column wrap

If you switch to flex-flow: column wrap, a grid-like layout is more attainable. However, a column-direction container has four potential problems right off the bat:

  1. Flex items flow vertically, not horizontally (like you need in this case).
  2. The container expands horizontally, not vertically (like the Pinterest layout).
  3. It requires the container to have a fixed height, so the items know where to wrap.
  4. As of this writing, it has a deficiency in all major browsers where the container doesn't expand to accommodate additional columns.

As a result, a column-direction container is not an option in this case, and in many other cases.


CSS Grid with item dimensions undefined

Grid Layout would be a perfect solution to your problem if the various heights of the content items could be pre-determined. All other requirements are well within Grid's capacity.

The width and height of grid items must be known in order to close gaps with surrounding items.

So Grid, which is the best CSS has to offer for building a horizontally-flowing masonry layout, falls short in this case.

In fact, until a CSS technology arrives with the ability to automatically close the gaps, CSS in general has no solution. Something like this would probably require reflowing the document, so I'm not sure how useful or efficient it would be.

You'll need a script.

JavaScript solutions tend to use absolute positioning, which removes content items from the document flow in order to re-arrange them with no gaps. Here are two examples:


CSS Grid with item dimensions defined

For layouts where the width and height of content items are known, here's a horizontally-flowing masonry layout in pure CSS:

grid-container {
  display: grid;                                                /* 1 */
  grid-auto-rows: 50px;                                         /* 2 */
  grid-gap: 10px;                                               /* 3 */
  grid-template-columns: repeat(auto-fill, minmax(30%, 1fr));   /* 4 */
}

[short] {
  grid-row: span 1;                                             /* 5 */
  background-color: green;
}

[tall] {
  grid-row: span 2;
  background-color: crimson;
}

[taller] {
  grid-row: span 3;
  background-color: blue;
}

[tallest] {
  grid-row: span 4;
  background-color: gray;
}

grid-item {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.3em;
  font-weight: bold;
  color: white;
}
<grid-container>
  <grid-item short>01</grid-item>
  <grid-item short>02</grid-item>
  <grid-item tall>03</grid-item>
  <grid-item tall>04</grid-item>
  <grid-item short>05</grid-item>
  <grid-item taller>06</grid-item>
  <grid-item short>07</grid-item>
  <grid-item tallest>08</grid-item>
  <grid-item tall>09</grid-item>
  <grid-item short>10</grid-item>
  <grid-item tallest>etc.</grid-item>
  <grid-item tall></grid-item>
  <grid-item taller></grid-item>
  <grid-item short></grid-item>
  <grid-item short></grid-item>
  <grid-item short></grid-item>
  <grid-item short></grid-item>
  <grid-item tall></grid-item>
  <grid-item short></grid-item>
  <grid-item taller></grid-item>
  <grid-item short></grid-item>
  <grid-item tall></grid-item>
  <grid-item short></grid-item>
  <grid-item tall></grid-item>
  <grid-item short></grid-item>
  <grid-item short></grid-item>
  <grid-item tallest></grid-item>
  <grid-item taller></grid-item>
  <grid-item short></grid-item>
  <grid-item tallest></grid-item>
  <grid-item tall></grid-item>
  <grid-item short></grid-item>
</grid-container>

jsFiddle demo


How it works

  1. Establish a block-level grid container. (inline-grid would be the other option)
  2. The grid-auto-rows property sets the height of automatically generated rows. In this grid each row is 50px tall.
  3. The grid-gap property is a shorthand for grid-column-gap and grid-row-gap. This rule sets a 10px gap between grid items. (It doesn't apply to the area between items and the container.)
  4. The grid-template-columns property sets the width of explicitly defined columns.

    The repeat notation defines a pattern of repeating columns (or rows).

    The auto-fill function tells the grid to line up as many columns (or rows) as possible without overflowing the container. (This can create a similar behavior to flex layout's flex-wrap: wrap.)

    The minmax() function sets a minimum and maximum size range for each column (or row). In the code above, the width of each column will be a minimum of 30% of the container and maximum of whatever free space is available.

    The fr unit represents a fraction of the free space in the grid container. It's comparable to flexbox's flex-grow property.

  5. With grid-row and span we're telling grid items how many rows they should span across.


Browser Support for CSS Grid

  • Chrome - full support as of March 8, 2017 (version 57)
  • Firefox - full support as of March 6, 2017 (version 52)
  • Safari - full support as of March 26, 2017 (version 10.1)
  • Edge - full support as of October 16, 2017 (version 16)
  • IE11 - no support for current spec; supports obsolete version

Here's the complete picture: http://caniuse.com/#search=grid


Cool grid overlay feature in Firefox

In Firefox dev tools, when you inspect the grid container, there is a tiny grid icon in the CSS declaration. On click it displays an outline of your grid on the page.

More details here: https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector/How_to/Examine_grid_layouts

@Oliver Joseph Ash 2018-01-03 16:27:45

Fantastic answer! With the "CSS Grid with item dimensions defined" solution, is it possible to express the height of a cell as a percentage of the cell width? This would be useful for displaying images, where the aspect ratio is known. We want to maintain the aspect ratio at all times.

@Michael_B 2018-01-03 16:34:28

Thanks. With respect to the aspect ratio issue for images, the "percentage of cell width" method (the percentage padding trick?), it is not reliable in Grid, or Flexbox, for that matter. See here and here. @OliverJosephAsh

@Oliver Joseph Ash 2018-01-03 16:50:45

Yes, I am referring to the percentage padding trick. Is it possible to use any of the workarounds in combination with your masonry layout solution? For context, we are looking to implement a CSS only masonry layout for the images on unsplash.com.

@Michael_B 2018-01-03 17:04:09

@OliverJosephAsh, the percentage padding trick, used with grid / flex items, fails in Firefox (and possibly other browsers). See the link references in my previous comment for the reasons. I would say JS is currently the safest route.

@Oliver Joseph Ash 2018-01-03 17:19:06

Unfortunately using JS for this is not an option. We want to enable server side rendering for performance and SEO reasons. This means the layout must be rendered before client-side JavaScript has downloaded, parsed, and executed. Given this seems to be impossible, I guess we'll have to make a trade off somewhere along the line! Thanks for your help :-)

@Michael_B 2018-05-10 17:20:22

Spec Update: In flexbox, percentage margins and paddings are now set to resolve again the container's inline size. drafts.csswg.org/css-flexbox/#item-margins @OliverJosephAsh

Related Questions

Sponsored Content

47 Answered Questions

[SOLVED] How can I transition height: 0; to height: auto; using CSS?

  • 2010-08-18 02:50:35
  • Hailwood
  • 955812 View
  • 1992 Score
  • 47 Answer
  • Tags:   css css-transitions

27 Answered Questions

[SOLVED] Set cellpadding and cellspacing in CSS?

24 Answered Questions

[SOLVED] How do I style a <select> dropdown with only CSS?

18 Answered Questions

[SOLVED] How do CSS triangles work?

28 Answered Questions

[SOLVED] How do I give text or an image a transparent background using CSS?

  • 2009-04-30 09:00:02
  • Stijn Sanders
  • 1513093 View
  • 2216 Score
  • 28 Answer
  • Tags:   html css opacity

35 Answered Questions

[SOLVED] Change an HTML5 input's placeholder color with CSS

19 Answered Questions

[SOLVED] Is it possible to apply CSS to half of a character?

31 Answered Questions

[SOLVED] Is there a CSS parent selector?

  • 2009-06-18 19:59:36
  • jcuenod
  • 1857020 View
  • 2991 Score
  • 31 Answer
  • Tags:   css css-selectors

Sponsored Content