CSS weekly #1: Masonry layout
I don’t have much time but want to write, so I’ll try to maintain a new section here—every week I’ll share with you my IRL CSS practice. Briefly.
Masonry layout with CSS Multi-column Layout
In order to achieve “masonry layout” we can use simple CSS Multiple Columns. You also can control when you want to break a column use the property -webkit-column-break-after: always; wrap this property inside a helper class .column-break
On the example below, we are breaking a column by using .column-break before card V and display: none this class for mobile phones by using media-queries.
For a long time, “Masonry” layout type was impossible in CSS, only by using JS and jQuery plugins in particularly.
Why CSS Columns
My first thought was “I should make it with grid layout”. But turned out that you can make columns and rows in grid layout — but you can’t make an automatic flow — only fixed values even if they flexible — from the one column to another. Grid layout has a strict pattern.
I found the example in this article and oh god, how complicated it was. Not flexible — each card has a fixed height and also flow was in the wrong direction. But it’s an interesting experiment but not for production.
CSS Multi-column Layout
Turns out that CSS Multi-column Layout is not a forgotten, old approach. Of course, I can’t say that I’m using CSS Grid Layout but it works as it should be, clear, simple and actually very smart. Also, CSS Multiple Columns has W direction, instead of Z direction.
Links
CSS Multi-column Layout Specification — https://drafts.csswg.org/css-multicol-1/#cc
CSS-TRICKS — https://css-tricks.com/almanac/properties/c/columns