I'm having some trouble creating a CSS grid where I can have an infinite number of rows, but only 2 columns per row. I'm unsure if I have my HTML set up correctly - I read that you have the CSS grid container (parent) and then the items (direct descendants), so I changed my HTML to reflect that. However, now all the repeated rows are collapsed into one.
My columns are an SVG image in one column, and then text in the second.
HTML
<div class="titles">
<svg name="svg-1"></svg>
<p class="emphasis-red">text 1</p>
<svg name="svg-2"></svg>
<p class="emphasis-red">text 2</p>
<svg name="svg-3"></svg>
<p class="emphasis-red">text 3</p>
<svg name="svg-4"></svg>
<p class="emphasis-red parent-text">text 4</p>
</div>
CSS
.titles {
display: grid;
grid-template-columns: [icon-start] 0.8em [text-start] auto [text-end];
grid-template-rows: repeat(auto-fit, [row-start] 100% [row-end]);
}
.titles svg {
grid-column: icon-start / text-column;
grid-row: row-start / row-end;
text-align: center;
width: 0.8em;
fill: $off-white;
height: 0.6em;
}
.titles p {
grid-column: text-start / text-end;
grid-row: row-start / row-end;
}
The grid is appearing like this, with all rows appearing on top of one another:
I thought that defining the rows as repeat(...)
, it would create 1 row for each svg
and p
, each of those occupying its own column. I believe the columns are set up correctly, but it seems it's only defined 1 row.
I'm a Node.js developer by trade, so Grid is new to me.
Your grid-template-rows
declaration is causing the problem. If you want both the number of rows and the height of those rows to be automatic (based on your content), then just leave this property with its default value of none
.
A basic grid is very simple to create. Generally the only styles you need are grid-template-columns
and gap
on the grid itself. The grid items don’t need any specific styling or placement, they just slot into their spots automatically.
.titles {
display: grid;
grid-template-columns: auto 1fr;
gap: 1em 0.5em;
}
.titles svg {
width: 1em;
aspect-ratio: 1;
background: pink;
}
.titles p {
margin: 0;
}
<div class="titles">
<svg></svg>
<p>text 1</p>
<svg></svg>
<p>text 2</p>
<svg></svg>
<p>text 3</p>
<svg></svg>
<p>text 4</p>
</div>