WANTED
I'd like to have a grid layout. A bit like Pinterest, except the items have fixed height (so it should be a lot easier).
It should be responsive. The number of colums should be set according to the viewport size.
The DOM should be a simple list of childs inside a container. I don't want a wrapper element for each row. What I want is this:
<div class="container">
<div class="item">a</div>
<div class="item">b</div>
<div class="item">c</div>
<div class="item">d</div>
<div class="item">e</div>
<div class="item">f</div>
<div class="item">g</div>
<div class="item">h</div>
<div class="item">i</div>
</div>
The ordering of items matter, so the "b" item of the DOM should be on the right of the "a" item (and not under).
MY ATTEMPT
I have done this layout using flexbox but it feels quite hacky as I have to compute some margins with maths. Also I don't understand how to control the vertical space between my flexbox rows, as it seems to grow with the container height.
Here is my LESS mixin of the Codepen above:
.flexboxGridMixin(@columnNumber,@spacingPercent) {
@contentPercent: 100% - @spacingPercent;
@sideMargin: @spacingPercent/(@columnNumber*2);
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
> * {
box-sizing: border-box;
width: (100% - @spacingPercent)/@columnNumber;
margin-left: @sideMargin;
margin-right: @sideMargin;
}
}
It seems doing math like that somehow defeat the initial purpose of flexbox no?
EXPECTED ANSWER
So, can someone explain me how to fix my flexbox layout? Or tell me what is the best, most elegant and modern way to solve this layout problem?
I don't want to use floats, probably not inline-block, nor JS based solution like Packery/Masonry
Please use modern CSS in your answers because I already know how to solve this with plain old CSS / JS. I target modern browsers only (to be defined)
Solution
Here is my final result, for those interested to reuse this layout.
Also a very nice visual Flexbox tutorial here: https://scotch.io/tutorials/a-visual-guide-to-css3-flexbox-properties