I want to create an arbitrary n x n matrix using CSS Grid. My HTML structure is:
<div class="matrix">
<div class="matrix-corner"></div>
<div class="matrix-header-row">Header1</div>
<div class="matrix-header-row">Header2</div>
<div class="matrix-header-col">Header1</div>
<div class="matrix-header-col">Header2</div>
<div class="matrix-row">
<div class="matrix-cell">100%</div>
<div class="matrix-cell">50%</div>
</div>
<div class="matrix-row">
<div class="matrix-cell">50%</div>
<div class="matrix-cell">100%</div>
</div>
</div>
Where the size of the matrix will ultimately be arbitrary (i.e. I can’t fix the number of columns in the grid CSS).
I can easily force the row and column headers to be in their respective places using grid-row: 1/2
and grid-column: 1/2
respectively – however I’m having difficulty fixing the matrix-row elements so that they stack one ontop of another; when I use grid-column: 2/-1
Chrome ignores the -1 (since it doesn’t relate to an explicit grid column?).
Here’s my full CSS:
.matrix {
display: grid;
grid-auto-flow: dense;
}
.matrix-corner {
grid-row: 1/2;
grid-column: 1/2;
}
.matrix-header-row {
grid-row: 1/2;
}
.matrix-header-col {
grid-column: 1/2;
}
.matrix-row {
grid-column: 2 / -1;
display: grid;
grid-template-columns: subgrid;
border: 1px solid red;
}
2
Answers
Need to wrap each row in a
matrix-row
container, but eachmatrix-cell
must be directly placed within the grid to ensure proper alignment.A
table
would probably be the proper element for this but you have selected CSS-Grid.As such, it would be appropriate to wrap "row title" in with the row contents.
Equally, wrapping the column headers in their own row make sense too.
Then we can leverage
auto-fit
(orauto-fill
) andsubgrid
.Then we only need to specify where rows start and end.
This permits us to dispose of the spacer div