tl;dr is there a way to align rows of a list of column objects in CSS?
I have a bunch of objects with properties that I want to show as separate elements on the page, however I want their properties to align together like a table.
A picture is worth a thousand words:
All the cells should align vertically, however the objects are defined as columns rather than rows.
Is there a way to achieve this with HTML/CSS?
The only way I could think of so far is to split the data, so the first property of all objects is defined in a row of cells, and the second property would be the second row, etc., with some padding between the columns. However that requires very messy code (JSX in this case) to populate the cells, such as a loop per property, and I am not sure if it can handle wrapping on overflow and such like modern grids/flexboxes can.
2
Answers
As per my commment above, subgrid would be ideal for this because, quite often, you wrap these comments in
divs
. However if you’re prepared to forgo wrapper divs you can replicate this just using grid itself by using grid-template-rows to control the height and using grid-auto-flow to set up a column-based layout. See an example of the code below.See CSS tricks for a good primer on grid and this video from Kevin Powell. Also this video for subgrid.
Edited to add
For any number of rows, use CSS custom properties and set that property in the style attribute of the parent wrapper
display: contents helps here, but check on caniuse.com that some feature you want in your real life example is properly implemented.
Here’s a simple 3 column (=3 ‘object’) example: