I am in need of creating a grid layout where each div is a specific width, and the number of rows depends on how many items there are. The twist is that I am unsure of the width of the outer container. My initial solution was to use CSS grid:
#container {
resize: both;
overflow: auto;
width: 170px;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(50px, 1fr));
}
#container div {
border: 1px solid red;
}
<div id="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</div>
However, my challenge now is to eliminate any empty cells in the grid for aesthetic reasons. To achieve this, I want to hide all elements on the last row, similar to the image below:
https://i.sstatic.net/lfTJu.png
This scenario with fitting three columns into the grid serves as only one example of the issue. If five columns can fit into the grid, then I aim to remove all items from the second row.
Is there a way to accomplish this using CSS without manually adding breakpoints or hiding items? Alternatively, could JavaScript provide a solution?
Please note that while I used css display:grid
in my demonstration, it is not mandatory - my main goal is achieving a grid-like appearance.