Reputation: 49
I'm currently attempting to make a CSS grid with a dynamic number of columns for an Angular app. Part of the grid should be divided into 1-to-n columns, depending on how many items are in a particular array. Each section should have a header as well, with the header for the dynamic section spanning all n columns. So, for an html page like this:
<div class="my-grid"
<div class="foo">
<div class="header">Foo</div>
<div class="cell-D" otherAttributes="otherValues"></div>
</div>
<div class="dynamic">
<div class="header">Foo</div>
<div class="cell-E" *ngFor="let object of objects" otherAttributes="otherValues">
</div>
<div class="bar">
<div class="header">Foo</div>
<div class="cell-F" otherAttributes="otherValues"></div>
</div>
</div>
...the result should look something like this:
One object in objects:
+---+---+---+
| A | B | C |
+---+---+---+
| D | E | F |
+---+---+---+
Two objects in objects:
+---+-------+---+
| A | B | C |
+---+---+---+---+
| D | E | E | F |
+---+---+---+---+
Three objects in objects:
+---+-----------+---+
| A | B | C |
+---+---+---+---+---+
| D | E | E | E | F |
+---+---+---+---+---+
etc.
...where A, B, and C are the headers, and D, E, and F correspond to their classes above.
Using repeat
for a grid-template requires a set number of columns, and setting it to auto
just makes all the columns stack vertically. Setting it to the maximum possible width leaves blank spaces if there aren't that many columns. I have tried using a subgrid within cell E to contain the columns, but the results were the same.
Is there a way I can get the CSS grid-template to allow for varying numbers of columns based on *ngFor
?
Thank you!
Upvotes: 0
Views: 1090
Reputation: 1685
You can do it like so:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.my-grid {
display: grid;
grid-template-columns: 300px 1fr 300px;
grid-template-rows: 1fr 1fr;
width: 900px;
min-width: max-content;
text-align: center;
}
.my-grid>* {
height: 300px;
display: grid;
place-items: center;
border: 1px solid black;
}
.dynamic {
display: flex;
}
.dynamic>div {
border: 1px solid black;
width: 300px;
height: 100%;
display: grid;
place-items: center;
}
<div class="my-grid">
<div class="A">
A
</div>
<div class="B">
B
</div>
<div class="C">
C
</div>
<div class="D">
D
</div>
<div class="dynamic">
<div>E</div>
<div>E</div>
<div>E</div>
<div>E</div>
</div>
<div class="F">
F
</div>
</div>
What I did here is customize the grid's columns
. Setting grid-template-columns
with specific dimensions for the first and last cell, then use 1fr
for the middle part to allow it to stretch to accommodate the content's width should replicate the behavior you're looking for.
Upvotes: 1