I am looking to create a table with multiple columns that can handle dynamic data. The challenge is that using the base <table>
element would cause the column width to change when the content changes and I also need the ability to hide columns using JavaScript.
As a result, I have opted to build a flexbox-based table. However, I am facing difficulties in managing column widths when hiding some of them.
For instance, consider the following table:
.table {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
width: 100%;
min-height: 200px;
}
.row {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
}
.table-head {
color: #a4a;
font-weight: 500;
}
.table-cell {
padding: 10px;
flex-grow: 1;
width: 100%;
overflow: hidden;
}
.table-cell:nth-child(1) {
width: 20%;
}
.table-cell:nth-child(2) {
width: 10%;
}
.table-cell:nth-child(3) {
width: 30%;
}
.table-cell:nth-child(4) {
width: 20%;
}
.table-cell:nth-child(5) {
width: 20%;
}
In this example, I want to hide the 4th column. As a result, there will be extra space that needs to be redistributed among the remaining columns while maintaining their relative sizes. How can I achieve this? For instance, ensuring that the "Address" column is larger than the "Country" column. Additionally, if only one column remains, it should take up 100% of the width.
I attempted to use flex-grow
to control the width distribution but encountered issues where the columns were not equal in size between the header row and body rows, leading to a lack of consistency in the table layout when columns are hidden.