From this answer:
In CSS, once the browser renders the page on the initial cascade, it doesn't reflow the document when an element wraps. As a result, parent elements don't know when their children wrap.
That's why containers don't shrink-to-fit their content after wrapping.
That's why you need media queries or JavaScript.
Knowing that, here's an example of using JavaScript to insert your dividers when necessary.
var items = document.querySelectorAll(".item");
var firstItemInCurrentRow = items[0];
items.forEach(item => {
// Check if the current item is at the same
// height as the first item in the current row.
if (item.offsetTop === firstItemInCurrentRow.offsetTop) {
// Don't apply the style to the first item
// in the current row.
if (item !== firstItemInCurrentRow) {
// Add the divider.
item.style.borderLeft = "1px solid black";
item.style.paddingLeft = "5px";
}
}
else {
// This item was lower, it must be
// the first in a new row.
firstItemInCurrentRow = item;
}
});
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
background-color: lightgray;
width: 100%;
}
.item {
flex-basis: 200px;
background-color: darkgray;
}
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
</div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…