W3C home > Mailing lists > Public > public-css-archive@w3.org > October 2017

Re: [csswg-drafts] [css-grid][css-flexbox] Pinterest/Masonry style layout support

From: Andy Barefoot via GitHub <sysbot+gh@w3.org>
Date: Sat, 07 Oct 2017 20:07:57 +0000
To: public-css-archive@w3.org
Message-ID: <issue_comment.created-334962477-1507406863-sysbot+gh@w3.org>
I'm no expert at either CSS or JavaScript but I think its possible to get a nice Masonry-like  solution which uses just a small amount of JavaScript but relies mostly on the CSS Grid functionality.

If each item is the same width (1 column) you can specify the row height of the grid to be something fairly small (say 20 pixels) and then set each item individually to span the optimum number of rows for its content then you get a Masonry layout with the CSS Grid benefits:
 - responsive "auto-fill" the number of columns
 - the "dense" packing automatically gives the correct Masonry ordering defined above

The disadvantage is that the height of each item will be a multiple of the row height (and row gap) and not the exact height of the content. This makes it better for content that is text, or text and image, and not perfect for just images of unpredictable heights.

The JavaScript to loop through all the items and calculate, then set, the correct row span is easy and needs to be done once on page load.
If the items will contain images then you should resize each item again once the image has loaded. 
If you are using minmax to give variable column sizes you may want to run the loop again on resize as the width of the columns may change and hence the height of the content.

Even if you do have items of different widths the dense packing still does a good job of creating a gap-free layout although you won't maintain the strict order of your items. In this case a larger row height will result in less gaps in the grid (but more white space at the bottom of each item) and a smaller row height will result in more (smaller) gaps in the grid.

Here's my attempt at both fixed-width and multi-width items. Please let me know if you see any flaws or advantages in this approach.

Fixed width: https://codepen.io/andybarefoot/pen/RLRPQL
Multi width: https://codepen.io/andybarefoot/pen/xLvPOE

-- 
GitHub Notification of comment by andybarefoot
Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/945#issuecomment-334962477 using your GitHub account
Received on Saturday, 7 October 2017 20:07:49 UTC

This archive was generated by hypermail 2.4.0 : Tuesday, 5 July 2022 06:41:19 UTC