Making Material Table columns dynamic width to content

14,947

Solution 1

Assuming that you do mean the angular material table, this one might help: md-table - How to update the column width

Solution 2

I used this successfully with Angular10.

First, wrap your table with a div, like this:

<div class='table-responsive'>
   <mat-table>
      ....
   </mat-table>
</div>

then add this CSS

.table-responsive {
 display: block;
 width: 100%;
 overflow-x: auto;
}

.mat-table {
 width: 100%;
 max-width: 100%;
 margin-bottom: 1rem;
 display: table;
 border-collapse: collapse;
 margin: 0px;
}

.mat-row,
.mat-header-row {
 display: table-row;
}

.mat-cell,
.mat-header-cell {
 word-wrap: initial;
 display: table-cell;
 padding: 0px 5px;
 line-break: unset;
 width: auto;
 white-space: nowrap;
 overflow: hidden;
 vertical-align: middle;
}

This will size the cells according to the content, and make your table horizontally scrollable!

Share:
14,947
Marshall Tigerus
Author by

Marshall Tigerus

Software Engineer

Updated on June 04, 2022

Comments

  • Marshall Tigerus
    Marshall Tigerus almost 2 years

    After a lot of tinkering I finally have a decent setup for my material table. It's got pagination, it's got sort, it's got all the goodies I need. However, it looks off because several of my columns are single digit values, and they have the same width as columns I would prefer to be larger (like the description which is wrapped excessively).

    Being inexperienced in scss (and css for that matter) I'm at a loss for how to fix this. I attempted tinkering with the flex property in just about every way I could figure out, and it doesn't appear to change a thing on the table.

    This issue is further complicated in that I cannot easily use the 'hack' of the material table generating classes based on the column identifier, as the columns are generated dynamically. I could pass in width information as well, but that seems like an unmaintainable hack.

    Is there a way to apply styling to the entire table and header that would get me the desired look?