I’d like to keep it at a height of 3 rows, regardless of how many items are in the grid. The grid should scroll if there are more than 3 rows worth of content. How can I do this, without manually setting the height to X pixels?
I have a grid like this:
const grid = document.getElementById("grid");
for (let i = 1; i <= 9; i++) {
const item = document.createElement("div");
item.innerHTML = i;
grid.appendChild(item);
}
#grid {
display: grid;
gap: 2px;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
width: 300px;
border: 3px solid blue;
overflow-y: scroll;
}
#grid>div {
background-color: #ccc;
display: flex;
justify-content: center;
align-items: center;
aspect-ratio: 16 / 9;
}
<div id="grid">
</div>
2
Answers
I wonder if
grid-auto-flow: column
would suit your needs:There is no way to structure CSS Grid to show only a certain number of rows. The height of the container must be restricted before the content can overflow the boundary. The height will have to be calculated based on the height of the cells/rows.
For this particular example, the height of the grid can be set by declaring the same aspect ratio that you have for
div
.To compensate for the row gaps, a calculation would need to be used for
height
instead of usingaspect-ratio
.I’m not sure if the given width of the grid and aspect ratio of the cells is what you are actually using or if it was just to create boxes for this example. Essentially, the height of the rows must be known in order to calculate the height of three rows for the height of the grid.