Search code examples
htmlcsshtml-tablecss-grid

How to align text horizontally across vertical stacked buttons/list-items which might have 2-3 lines


I'm trying to create a layout which is basically a table/css-grid which auto aligns text horizontally across multiple rows. The rows/list-items should be clickable and tabbable via tabindex and have some border and alternating backgrounds.

enter image description here

Although the text in the columns is the same in this example it won't be in the actual application. There might be a longer number in the first column, a shorter in the second, a longer in the third or even some text, so I need the layout to auto align those column widths. Red lines are just for illustration.

This is no problem as long as I'm only having one row of content within the list-item but how can I solve this problem when I'm having multiple rows? If this was a table layout what I need would be grouping two <tr>'s together in terms of tabindex/focus, onclick and visuals.

I could group them with a display: contents; container around them and still style them via .contents-selector > * in terms of the background and the border I guess, but I can't make it tabbable or clickable on the .contents-selector class.

Maybe there is a whole different approach to this, I'm not thinking about. I can of course achieve my layout with some hacky stuff like using tables for the layout, position: absolute; on the longer text and <br>'s on another column etc. while having the tabindex and onclick on the tr although I wouldn't know how many lines I get and how many <br>'s I would need but that can't be the right solution to this problem.

Edit: Solution was the usage of tbody: https://stackoverflow.com/a/76546055/1900980


Solution

  • You can use a simple html table for this and put each row or row-groups inside a tbody. you can now use the tbodyto style or setonclicklisteners ortab-index`

    table,
    tr,
    td
    {
        border: 1px solid gray;
    }
    
    table tbody:nth-child(even)
    {
        background-color: aqua;
    }
        <table>
        <tbody>
            <tr>
                <td>Lorem.</td>
                <td>Qui?</td>
                <td>Consequatur!</td>
            </tr>
        </tbody>
    
        <tbody>
            <tr>
                <td>Lorem, ipsum.</td>
                <td>Neque, enimssssssssssssss.</td>
                <td>Aut, vitae!</td>
            </tr>
            <tr>
                <td>Lorem, ipsum.</td>
                <td>Neque, enim.</td>
                <td>Aut, vitae!</td>
            </tr>
        </tbody>
        <tbody>
            <tr>
                <td>Lorem.</td>
                <td>Qui?</td>
                <td>Consequatur!</td>
            </tr>
        </tbody>
    </table>