CSS grid with data grouped by rows
Asked Answered
N

1

6

I've been giving display: grid a test drive for the last few hours and haven't found a working example of how to keep your data grouped by rows (which seems like a very common use-case). I'm trying to replace a table layout with a CSS Grid but can't quite hack it.

Consider this HTML:

<div class="wrapper">
    <div class="row">
         <div class="col1">Short Data</div>
         <div class="col2">Very Much Longer Data</div>
    </div>
    <div class="row">
         <div class="col1">Short Data</div>
         <div class="col2">Regular Data</div>
    </div>
</div>

And this CSS:

.wrapper {
    display: grid;
    grid-template-columns: 1fr 1fr;
}

The above CSS will only affect the rows but not lay out the columns. If I nest another grid inside each row then the data points have no relationship and won't expand in unison (until subgrid).

There are a few reasons why this matters to me:

  1. I would like each row to be a React component which requires a single outer wrapper tag.
  2. I'm looping over a data set of unknown length and React requires a key on each iteration.
  3. I would like to create zebra stripes or hover events that respond on a per row basis.
  4. My OCD doesn't like all children living next to each other without some sort of grouping.

Should I just use good-ol tables?

Nerveless answered 11/10, 2019 at 18:13 Comment(1)
Frankly CSS-Grid is not intended to replace tables. I'd stick with what works and is semantically correctKareykari
K
2

The CSS subgrid feature is part of Level 2 of the css grid specs and does exactly what you require. It allows you to set:

grid-template-columns: subgrid

on the group container (i.e. row). The group container then uses the same grid as it's parent, including resizing the columns across all group containers.

However, the feature doesn't have sufficient browser support yet, so we'll have to wait.

Katheryn answered 31/1, 2023 at 8:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.