Expandable Table Row | CSS Grid

ADITYA CHHIKARA
3 min readMay 5, 2020

--

How to expand a table row in html

Why expanded table row?

Sometimes we have need to abstract some information in a table as it may take large space. But this information is important and we need to show when user wants to know more about that record.

Let’s take an example to explain. Suppose we want to display an entity may be users having multiple records. In abstract view we want to show only user id, user name, email and mobile. But there are other information for each user, which we can’t show in a table row as it may take large space or may be it not useful until user wants to know more about some particular record.

So we can display this secondary type of information inside in an expanded row.

Expanding a table row -

Now let’s write some code to expand a table row. We will use grid system to do this task. Let’s create our required table in four steps-

  1. Row as Grid — In first step we will make our table row as grids and will provide styling for n-1 columns.
tr {
display: grid;
grid-template-columns: repeat(3, 1fr);
}

So providing track size for three columns/n-1, last one will be pushed to the next line.

2. Hide Row — In step 2 we will hide content of our last cell, which is already pushed to next line. This will be its default state.

.hide-row {
display: none;
}

3. Row width — In third step we will use few more styling from grid system. Using this style we will allow last cell to take full width which will be equal to combined width of n-1 columns.

.expanded-row-content {
display: grid;
grid-column: 1/-1;
}

property grid-column 1/-1 will allow our last cell to take full width and it will look like a row.

So now our expandable row table is complete but we need few more events and styling to work it properly.

4. Toggle row — In fourth step we will add an on click event to each row.

const toggleRow = (element) => {
element.getElementsByClassName(‘expandable-row’).
[0].classList.toggle(‘hide- row’);
}

This function will toggle hide- row class for last cell inside current row, on which we are clicking. As initially expended cell was in hidden state, on clicking on row hide-row class will get removed and it will start showing. And on clicking again hide-row class will be added and it will get toggle and hide.

Useful links —

Complete code — https://github.com/chhikaradi1993/Expandable-table-row/blob/master/index.html

--

--