I suppose that is not possible to obtain the desired result simply using one of the known layout modes (flexbox, grid-layout, inline, ...) nor using CSS columns. Every solution will lead to an unwanted result.
But you can obtain the result using a combination of CSS grid-layout and Javascipt code.
This is the wrapper CSS style block:
#wrapper{
width: 200px; /* CSS grid-layout will expand contained divs to cover this size */
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* "1fr" for each column */
grid-column-gap: 10px;
grid-row-gap: 5px;
}
And this is the Javascript code (add it after #wrapper is closed):
"strict mode";
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
function compute_gaps(a) {
let max = a.max();
return a.map(function(el) {
return el - max;
});
}
function compose_gaps(a, b) {
return b.map(function(el, i) {
return a[i] + el;
});
}
var counter = 0;
var columns = 3; // number of columns
var gaps = [];
var heights = [];
for (let el of document.querySelectorAll("#wrapper > div")) {
let colIdx = counter % columns;
if (counter % columns === 0) {
//compute gaps
if (counter) gaps.push(compute_gaps(heights));
if (gaps.length > 1) {
gaps[gaps.length - 1] = compose_gaps(
gaps[gaps.length - 1],
gaps[gaps.length - 2]
);
}
heights = [];
}
if (gaps.length) {
el.style.marginTop = gaps[Math.floor(counter / columns - 1)][colIdx];
}
heights.push(el.offsetHeight); // apply gap as margin
counter++;
}
Tested the code in a little more complex situation and worked in this way.
The code computes, in each row, gaps between the highest block and the others in the row (compute_gaps); after that, applied the gap as a CSS margin-top. Gaps are summed with the previous ones (compose_gaps).
I hope this answers your question.