Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a table using definition list and grid layout

Tags:

html

css

css-grid

Here is my attempt to create pseudo-table, using <dl> and display: grid.

Actually, it works. The only problem, is that I forced to use ugly way to define rows. It is completely manual way. So if I have 30 rows in table, it will be really very dumb to repeat dt + dd + ... + dd for each of them.

How this issue could be fixed?

(I don't want to use real tables, because it is for Markdown).

dl {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
}

dt {
    text-align: center;
}

dd {
    margin-left: 0;
}

dt, dd {
    border: 1px solid lightgray;
    padding: 0 1em;
}

/* Ugly part
 * (Red, yellow, and green colors are just for demo)
 */

dt {
    grid-row-start: 1;
}

dt + dd {
    grid-row-start: 2;
    color: rgb(244, 67, 54);
}

dt + dd + dd {
    grid-row-start: 3;
    color: rgb(255, 152, 0);
}

dt + dd + dd + dd {
    grid-row-start: 4;
    color: rgb(76, 175, 80);
}
<dl>
    <dt><p>Term 1</p></dt>
    <dd>
        <p>Definition of term 1 long long long long</p>
        <p>Lorem ipsum...</p>
        <p>Lorem ipsum...</p>
        <p>Lorem ipsum...</p>
    </dd>
    <dd><p>Definition of term 1</p></dd>
    <dd><p>Definition of term 1</p></dd>

    <dt><p>Term 2</p></dt>
    <dd><p>Definition of term 2</p></dd>
    <dd><p>Definition of term 2</p></dd>
    <dd><p>Definition of term 2</p></dd>

    <dt><p>Term 3</p></dt>
    <dd><p>Definition of term 3</p></dd>
    <dd><p>Definition of term 3</p></dd>
    <dd><p>Definition of term 3</p></dd>
</dl>
like image 476
user90726 Avatar asked May 23 '17 12:05

user90726


1 Answers

Assuming... you're on Firefox or Chrome but not IE/Edge :p, here's a working solution with any number of terms and any number of definitions for each term:

➡️ Codepen

Explanations:

  1. filling the grid column after column ➡️ grid-auto-flow: column;
  2. (grid items) each term should be on row 1, so its definitions are below it ➡️ dt { grid-row-start: 1 } acts like "next column please"
  3. Create enough explicit rows (say, 50) but the row N+1 should show (have any height) only if any given term has at least N definitions (4 rows visible if the max definitions for a given term is 3. None has 4) ➡️ grid-template-rows: repeat(50, min-content);
  4. Then tried to have an undefined number of columns/terms but I couldn't achieve it with explicit columns (I wanted something like "1fr if there's content but 0 otherwise" with minmax(), min|max-content to no avail). Worked like a charm with implicit columns though: ➡️ grid-auto-columns: 1fr;

dl {
    display: grid;
    grid-auto-flow: column;
    /* doesn't assume 3 terms but N */
    grid-auto-columns: 1fr;
    grid-template-rows: repeat(50, min-content); /* doesn't assume 3 defs but M<50 */
}

dt {
    grid-row-start: 1; /* reset, next column */
}
like image 83
FelipeAls Avatar answered Sep 22 '22 06:09

FelipeAls