Subgrid for Nested Alignment

snippet

Say we have a list of value groups:

  1. πŸ“ 30 πŸ“ 30 πŸ”— 7
  2. πŸ“ 70 πŸ“ 43.5 πŸ”— 17
  3. πŸ“ 83.5 πŸ“ 100 πŸ”— 49

Similar fields should be aligned for visual consistency; vertically stacked (i.e. columns).

We cannot make assumptions about fields’ values, so assigning fixed widths is not an option.

<table> seems the obvious solution, but is semantically undesirable in this case (in part because text messages might be interspersed among tabular data).

πŸ“ 30 πŸ“ 30 πŸ”— 7
πŸ“ 70 πŸ“ 43.5 πŸ”— 17
πŸ“ 83.5 πŸ“ 100 πŸ”— 49

Let’s assume that display: table is equally undesirable.

That leaves subgrid:

  1. πŸ“ 30 πŸ“ 30 πŸ”— 7
  2. πŸ“ 70 πŸ“ 43.5 πŸ”— 17
  3. πŸ“ 83.5 πŸ“ 100 πŸ”— 49

This also allows us to add arbitrary text content in between tabular items:

  1. πŸ“ 30 πŸ“ 30 πŸ”— 7
  2. πŸ“ 70 πŸ“ 43.5 πŸ”— 17
  3. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
  4. πŸ“ 83.5 πŸ“ 100 πŸ”— 49

(Note that we added an extra column to avoid unnecessarily extending tabular items.)

.grid {
    --cell-padding: calc(0.5 * var(--spacing)) var(--spacing);
    --cell-border: 1px dashed #CCC;

    display: inline-grid;
    grid-template-columns: repeat(4, auto);
    padding-inline: 0;
    list-style-type: none;

    > * {
        grid-column: 1 / -1;
    }
    > .text {
        font-size: small;
    }
    > :not(.text) {
        display: grid;
        grid-template-columns: subgrid;

        > * {
            border: var(--cell-border);
            padding: var(--cell-padding);

            & + * {
                border-left: none; /* collapse */
            }
        }
        & + * > * {
            border-top: none; /* collapse */
        }

        > :nth-child(1) {
            grid-column: 1 / 2;
        }
        > :nth-child(2) {
            grid-column: 2 / 3;
        }
        > :nth-child(3) {
            grid-column: 3 / 4;
        }
    }
}